Click here to Skip to main content
14,603,886 members
Rate this:
Please Sign up or sign in to vote.
Hi everyone!

I am working on an element of a project that has to do with FTP uploading files. This is the code that I have to upload all types of files.

#region FTP Upload
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpSite + Path.GetFileName(newFile));
request.Method = WebRequestMethods.Ftp.UploadFile;

request.Credentials = new NetworkCredential(ftpUserNameTextBox.Text.Trim(), ftpPasswordTextBox.Text.Trim());

// Copy the contents of the file to the request stream.
StreamReader sourceStream = null;

sourceStream = new StreamReader("where-file-is-stored" + newFile);

byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
request.KeepAlive = true;
request.ReadWriteTimeout = 1200000; // 20 minutes
sourceStream.Close();
request.ContentLength = fileContents.Length;

Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

response.Close();
#endregion


All types of files seem to be ok if I re-download them after being uploaded. However, if I download a .sdf (SQL Server CE) file after it is uploaded with this code, it seems to be getting corrupted. Is there a setting that I'm missing that will keep these types of files from getting corrupted?

Thanks so much everyone!
Posted
Updated 20-Feb-17 3:42am

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

You should use a BinaryReader instead of a stream reader. You are converting all the bytes to UTF-8 and probably screwing up anything that is binary since it is probably detecting a different encoding. With BinaryReader you don't need to use the Encoding.UTF8.GetBytes, just use the methods on the reader to read the raw bytes.
   
Comments
Sergey Alexandrovich Kryukov 19-Jul-13 19:08pm
   
Good idea, a 5. The use of text-mode FTP is rare these days and rarely makes sense.
—SA
joshrduncan2012 22-Jul-13 10:36am
   
I needed a BinaryReader evidently. Thanks Ron!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100