1

我有的:

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

4

3 回答 3

2

使用 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 下载目录

于 2017-12-04T07:57:22.633 回答
0

您需要调用GetResponse,然后您将有权访问包含您的内容的响应流,然后您可以将该流写入您要保存的文本文件中。

这里似乎有一个非常充实的示例(它在 C# 中,但我认为应该很容易翻译成 VB)。

于 2012-12-07T22:24:02.853 回答
-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()
于 2012-12-07T23:27:06.793 回答