How to download file from FTP and upload it again

最后都变了- 提交于 2019-12-08 03:47:36

问题


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.


回答1:


Some links:

VB.NET: http://www.codeproject.com/KB/IP/FtpClient.aspx

c#: http://www.c-sharpcorner.com/uploadfile/neo_matrix/simpleftp01172007082222am/simpleftp.aspx




回答2:


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:

  • Upload file to FTP site using VB.NET
  • Download all files and sub-directories from FTP folder in VB.NET


来源:https://stackoverflow.com/questions/2450032/how-to-download-file-from-ftp-and-upload-it-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!