如何从FTP下载文件并再次上传

时间:2010-03-15 19:52:58

标签: .net vb.net ftp ftpwebrequest

我需要从FTP服务器下载文件并对其进行一些更改,然后使用VB.NET将其再次上传到同一个FTP。

请帮忙。谢谢。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

如果您只想直接重新上传文件,只需将下载流传输到上传流:

Dim downloadRequest As FtpWebRequest =
    WebRequest.Create("ftp://downloadftp.example.com/source/path/file.txt")
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
downloadRequest.Credentials = New NetworkCredential("username1", "password1")

Dim uploadRequest As FtpWebRequest =
    WebRequest.Create("ftp://uploadftp.example.com/target/path/file.txt")
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile
uploadRequest.Credentials = New NetworkCredential("username2", "password2")

Using downloadResponse As FtpWebResponse = downloadRequest.GetResponse(),
      sourceStream As Stream = downloadResponse.GetResponseStream(),
      targetStream As Stream = uploadRequest.GetRequestStream()
    sourceStream.CopyTo(targetStream)
End Using

如果你需要以某种方式处理内容,或者你需要监视进度,或者两者兼而有之,你必须按块(或者一行一行,如果它是一个文本文件,你正在处理它) ):

Dim downloadRequest As FtpWebRequest =
    WebRequest.Create("ftp://downloadftp.example.com/source/path/file.txt")
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
downloadRequest.Credentials = New NetworkCredential("username1", "password1")

Dim uploadRequest As FtpWebRequest =
    WebRequest.Create("ftp://uploadftp.example.com/target/path/file.txt")
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile
uploadRequest.Credentials = New NetworkCredential("username2", "password2")

Using downloadResponse As FtpWebResponse = downloadRequest.GetResponse(),
      sourceStream As Stream = downloadResponse.GetResponseStream(),
      targetStream As Stream = uploadRequest.GetRequestStream()
    Dim buffer As Byte() = New Byte(10240 - 1) {}
    Dim read As Integer
    Do
        read = sourceStream.Read(buffer, 0, buffer.Length)
        If read > 0 Then
            ' process "buffer" here
            targetStream.Write(buffer, 0, read)
        End If
    Loop While read > 0
End Using

另见: