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.