The most trivial way to download a binary file from an FTP server using VB.NET is using WebClient.DownloadFile
:
Dim client As WebClient = New WebClient()
client.Credentials = New NetworkCredential("username", "password")
client.DownloadFile(
"ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")
If you need a greater control, that WebClient
does not offer (like TLS/SSL encryption, ascii/text transfer mode, resuming transfers, etc), use FtpWebRequest
. Easy way is to just copy an FTP response stream to FileStream
using Stream.CopyTo
:
Dim request As FtpWebRequest =
WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.DownloadFile
Using ftpStream As Stream = request.GetResponse().GetResponseStream(),
fileStream As Stream = File.Create("C:\local\path\file.zip")
ftpStream.CopyTo(fileStream)
End Using
If you need to monitor a download progress, you have to copy the contents by chunks yourself:
Dim request As FtpWebRequest =
WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.DownloadFile
Using ftpStream As Stream = request.GetResponse().GetResponseStream(),
fileStream As Stream = File.Create("C:\local\path\file.zip")
Dim buffer As Byte() = New Byte(10240 - 1) {}
Dim read As Integer
Do
read = ftpStream.Read(buffer, 0, buffer.Length)
If read > 0 Then
fileStream.Write(buffer, 0, read)
Console.WriteLine("Downloaded {0} bytes", fileStream.Position)
End If
Loop While read > 0
End Using
For GUI progress (WinForms ProgressBar
), see (C#):
FtpWebRequest FTP download with ProgressBar
If you want to download all files from a remote folder, see
How to download directories from FTP using VB.NET