Visual Basic FtpWebRequest下载文件?

时间:2012-12-07 21:26:06

标签: .net vb.net ftp 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,但只能下载/上传一次,因为我不知道如何摆脱这种连接。

3 个答案:

答案 0 :(得分:1)

使用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。简单的方法是使用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

答案 1 :(得分:0)

您需要拨打GetResponse,然后您才能访问包含您内容的响应流,然后您可以将该流写入要保存的文本文件中。

似乎有一个pretty well fleshed out sample here(它在C#中,但我认为应该很容易转换为VB)。

答案 2 :(得分:-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()