C# FtpWebRequest creates corrupted files <p>I'm using .NET 3.5 and I need to transfer by FTP some files. I don't want to use files because I manage all by using <code>MemoryStream</code> and <code>bytes arrays</code>.</p> <p>Reading these articles (<a href="http://www.joemoceri.com/uploading-files-to-ftp-using-csharp/" rel="nofollow noreferrer">article</a> and <a href="http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class" rel="nofollow noreferrer">article</a>), I made my client.</p> <pre><code>public void Upload(byte[] fileBytes, string remoteFile) { try { string uri = string.Format("{0}:{1}/{2}", Hostname, Port, remoteFile); FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(uri); ftp.Credentials = new NetworkCredential(Username.Normalize(), Password.Normalize()); ftp.UseBinary = true; ftp.UsePassive = true; ftp.Method = WebRequestMethods.Ftp.UploadFile; using (Stream localFileStream = new MemoryStream(fileBytes)) { using (Stream ftpStream = ftp.GetRequestStream()) { int bufferSize = (int)Math.Min(localFileStream.Length, 2048); byte[] buffer = new byte[bufferSize]; int bytesSent = -1; while (bytesSent != 0) { bytesSent = localFileStream.Read(buffer, 0, bufferSize); ftpStream.Write(buffer, 0, bufferSize); } } } } catch (Exception ex) { LogHelper.WriteLog(logs, "Errore Upload", ex); throw; } } </code></pre> <p>The FTP client connects, writes and close correctly without any error. But the written files are corrupted, such as PDF cannot be opened and for DOC/DOCX Word shows a message about file corruption and tries to restore them.</p> <p>If I write to a file the same bytes passed to the Upload method, I get a correct file. So the problem must be with FTP transfer.</p> <pre><code>byte[] fileBytes = memoryStream.ToArray(); File.WriteAllBytes(@"C:\test.pdf", fileBytes); // --&gt; File OK! ftpClient.Upload(fileBytes, remoteFile); // --&gt; File CORRUPTED on FTP folder! </code></pre>