最平凡的方式來使用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
不提供,請使用FtpWebRequest
。簡單的方法是隻是一個FTP響應流中使用Stream.CopyTo
複製到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