使用 VB.NET 从 FTP 服务器下载二进制文件最简单的方法是使用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")
如果您需要WebClient 不提供的更大控制(如TLS/SSL encryption、ascii/文本传输模式、resuming transfers 等),请使用FtpWebRequest。简单的方法是使用 Stream.CopyTo 将 FTP 响应流复制到 FileStream:
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
如果你需要监控一个下载进度,你必须自己分块复制内容:
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
有关 GUI 进度 (WinForms ProgressBar),请参阅 (C#):
FtpWebRequest FTP download with ProgressBar
如果您想从远程文件夹下载所有文件,请参阅
How to download directories from FTP using VB.NET