Nov
19
Written by:
Briana Tarrance
11/19/2008 3:03 PM
With the help of the .NET framework, it is simple to download files via FTP sessions programmatically. In this example, I am going to download a stylesheet from my FTP directory and display it in the console window.

Figure 1: FTP Directory Showing File To Download
Imports System.IO
Imports System.Net
.....
Public Sub GetFileFromFTP(ByVal ServerPath As String)
Dim localfile As String = "C:\ftpTest.css"
ServerPath = "ftp://ftp.virtual-essentials.com/Directory/skin.css"
'Create/Instantiate Object for Communicating with the server
Dim myRequest As FtpWebRequest = FtpWebRequest.Create(ServerPath)
myRequest.Method = WebRequestMethods.Ftp.DownloadFile
myRequest.KeepAlive = False 'turn off when action completes.
myRequest.UseBinary = True 'binary, not text transfer
'Pass credentials
myRequest.Credentials = New NetworkCredential("username", "password")
'Create/Instantiate the response back from the server by getting the response to your request and casting as a web response
Dim myResponse As FtpWebResponse = CType(myRequest.GetResponse, FtpWebResponse)
'Get the stream from the response and assign to a Stream Reader
Dim myResponseStream As Stream = myResponse.GetResponseStream
Dim myReader As StreamReader = New StreamReader(myResponseStream)
'read the response
Dim myFile As String = myReader.ReadToEnd()
Console.WriteLine(myFile)
'Check to see if download has completed by checking the Status
Dim status As String = myResponse.StatusDescription
'close the reader
myReader.Close()
'close the response
myResponse.Close()
End Sub
And here's the output:

Pretty Simple Right!
Copyright ©2008 Briana Tarrance
Tags: