Zip file is getting corrupted after uploaded to server using C#

前端 未结 1 1850
傲寒
傲寒 2020-12-30 07:08

I am trying to upload a zip file to server using C# (Framework 4)and following is my code.

string ftpUrl = ConfigurationManager         


        
相关标签:
1条回答
  • 2020-12-30 07:36

    This is the problem:

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

    StreamReader (and any TextReader) is for text data. A zip file isn't text data.

    Just use:

    byte[] fileContents = File.ReadAllBytes(fileToBeUploaded);
    

    That way you're not treating binary data as text, so it shouldn't get corrupted.

    Or alternatively, don't load it all into memory separately - just stream the data:

    using (var requestStream = request.GetRequestStream())
    {
        using (var input = File.OpenRead(fileToBeUploaded))
        {
            input.CopyTo(requestStream);
        }
    }
    

    Also note that you should be using using statements for all of these streams, rather than just calling Close - that way the resources will be disposed even if an exception is thrown.

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