C # - File corrupted after upload to server

I used the following source code to upload the excel and pdf file, but after the file was moved to the server, the file is corrupted. I think the problem is with the encoding process Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); but I don’t know how to resolve it.

 public static void sampleUpload() { // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://100.165.80.15:21/output/Group Dealer, Main Dealer, Zone, Branch, and Destination Report_20120927105003.pdf"); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("toc", "fid123!!"); // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader("D:\\Group Dealer, Main Dealer, Zone, Branch, and Destination Report_20120927105003.pdf"); 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(); } 
+2
c # file-upload ftp
source share
3 answers

Do not read binaries as text. Use the Stream.CopyTo method (or equivalent code if you cannot use .Net 4.0)

  using(StreamReader sourceStream = ...){ using(Stream requestStream = request.GetRequestStream()) { sourceStream.CopyTo(requestStream); } } 
+5
source share

You can try using BufferedStream, which handles raw bytes.

0
source share

In my situation, I could not use Stream.Copy, as Alex suggested in his answer, because I used the .NET Framework 2.0. Instead, I used only Stream to read binary files, since Streamreader is designed to read only text files:

 public static void sampleUpload() { // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://100.165.80.15:21/output/Group Dealer, Main Dealer, Zone, Branch, and Destination Report_20120927105003.pdf"); request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = true; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("toc", "fid123!!"); // Copy the contents of the file to the request stream. byte[] b = File.ReadAllBytes(sourceFile); request.ContentLength = b.Length; using (Stream s = request.GetRequestStream()) { s.Write(b, 0, b.Length); } FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); response.Close(); } 
0
source share

All Articles