2012-12-07 226 views
1

我有什麼:Visual Basic FtpWebRequest下載文件?

Dim ftploader As System.Net.FtpWebRequest = 
    DirectCast(System.Net.WebRequest.Create(
     "ftp://ftp.cabbageee.host-ed.me/nim/Vardelatestmessage.txt"), 
     System.Net.FtpWebRequest) 

ftploader.Credentials = 
    New System.Net.NetworkCredential("Insert Username here", "Insert password here") 

我想這.txt文件下載到我的c:驅動。我已經有一個連接,那麼如何保存.txt文件?另外,我怎樣才能上傳文件?我已經試過My.Computer.Network.DownloadFile,但只能下載/上傳一次,因爲我不知道如何擺脫這種連接。

回答

0

您需要撥打電話GetResponse,然後才能訪問將包含內容的響應流,然後將該流寫入要保存的文本文件。

似乎有一個pretty well fleshed out sample here(這是在C#中,但我覺得應該是很容易轉化爲VB)。

-1

試試這個:

Dim myWebClient As New System.Net.WebClient 
Dim webfilename As String = "http://www.whatever.com/example.txt" 
Dim file As New System.IO.StreamReader(myWebClient.OpenRead(webfilename)) 

gCurrentDataFileContents = file.ReadToEnd() 

file.Close() 
file.Dispose() 
myWebClient.Dispose() 
0

最平凡的方式來使用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