Zip file gets corrupted after upload to server using C #

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

 string ftpUrl = ConfigurationManager.AppSettings["ftpAddress"]; string ftpUsername = ConfigurationManager.AppSettings["ftpUsername"]; string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"]; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl + "Transactions.zip"); request.Proxy = new WebProxy(); //-----The requested FTP command is not supported when using HTTP proxy. request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); StreamReader sourceStream = new StreamReader(fileToBeUploaded); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); response.Close(); 

The mail file loads successfully, but when I tried to open the zip file from the server (manually), it showed me the Unexpected end of archive error.
For file compression I use Ionic.zip dll . Before transferring the zip file, I was able to successfully extract it.

Any help appreciated. Thank you

+7
source share
1 answer

This is the problem:

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

StreamReader (and any TextReader ) - for text data. Zip file is not text data.

Just use:

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

This way you do not treat binary data as text, so it should not be corrupted.

Or, on the contrary, do not load all this into memory separately - just transfer the data:

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

Also note that you should use using statements for all of these threads, not just calling Close - this way resources will be deleted even if an exception is thrown.

+14
source

All Articles