使用 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 加密、ascii/文本传输模式、恢复传输等),请使用FtpWebRequest
. 简单的方法是将 FTP 响应流复制到FileStream
使用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
如果您需要监控下载进度,您必须自己按块复制内容:
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
如果要从远程文件夹下载所有文件,请参阅
如何使用 VB.NET 从 FTP 下载目录