Archive or image is corrupted after uploading to FTP and downloading back with FtpWebRequest

后端 未结 1 1467
陌清茗
陌清茗 2020-12-11 12:29

I have two methods:

  1. Uploads files to the FTP Server
  2. Downloads Files from the Server.

Everything works perfectly with text or xml fil

相关标签:
1条回答
  • 2020-12-11 12:51

    You are uploading a binary file (a bitmap image) as if it were a text file in UTF-8 encoding:

    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    

    That naturally corrupts the file.

    You have to transfer binary files exactly as they are, bit by bit.

    Moreover your technique is quite inefficient for potentially large image files. You keep whole file in memory at least twice.

    The code, that you need, is actually much simpler than yours:

    using (Stream fileStream = File.OpenRead(FilePath + FileName)
    using (Stream ftpStream = request.GetRequestStream())
    {
        fileStream.CopyTo(ftpStream);
    }
    

    Your download code is ok, but again, it can be simplified to:

    using (Stream ftpStream = request.GetResponse().GetResponseStream())
    using (Stream fileStream = File.Create(Destination))
    {
        ftpStream.CopyTo(fileStream);
    }
    

    For a full code, see Upload and download a binary file to/from FTP server in C#/.NET.

    0 讨论(0)
提交回复
热议问题