How to download file from FTP and upload it again

2019-05-31 14:26发布

I need to download file from FTP server and make some changes on it and upload it again to the same FTP using VB.NET.

Any help please. Thank you.

2条回答
一夜七次
2楼-- · 2019-05-31 15:05

If you want to just directly re-upload the file, simply pipe the download stream to the upload stream:

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

If you need to process the contents somehow, or if your need to monitor the progress, or both, you have to do it chunk by chunk (or maybe line by line, if it is a text file, that you are processing):

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

See also:

查看更多
登录 后发表回答