I have very strange problem when I upload files to my FTP (zip or gif) files.
I am creating a zip file with code and upload it with code to FTP. I can open any of this files type when I create them on my local disk. But when I upload any of this to FTP and than download it show me a message for .zip file as “unexpected end of archive” , and for .gif file type after I download them and try to open in XP Windows picture and fax viewer “Drawing failed” :
I use this code for uploading to FTP:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.tim.com/" + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(ftpuser,ftppass);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(filePath +"\\"+ fileName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
request.KeepAlive = false;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
This code:
You’re reading the bytestream as text with a specific encoding (UTF8)… but GIF and ZIP are binary files, not text files. The encoding is mangling them.
Try using something like ReadAllBytes: