title: Upload and download a file to/from FTP server in C#/.NET
body: <p>I am using .NET 4 C#. I am trying to upload and then download a ZIP file to (my) server.</p>
  
  <p>For uploading I have</p>
  
  <pre><code>using (WebClient client = new WebClient())
  {
      FtpWebRequest request = (FtpWebRequest)WebRequest.Create(MyUrl);
      request.Method = WebRequestMethods.Ftp.UploadFile;
      request.EnableSsl = false;
      request.Credentials = new NetworkCredential(MyLogin, MyPassword);
      byte[] fileContents = null;
      using (StreamReader sourceStream = new StreamReader(LocalFilePath))
      {
          fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
      }
      request.ContentLength = fileContents.Length;
      using (Stream requestStream = request.GetRequestStream())
      {
          requestStream.Write(fileContents, 0, fileContents.Length);
      }
      FtpWebResponse response = null;
      response = (FtpWebResponse)request.GetResponse();
      response.Close();
  }
  </code></pre>
  
  <p>This seems to work, in that I get a file on the server of the right size.</p>
  
  <p>1) How do I stream it, rather than load it into memory first?  I will be uploading very large files.</p>
  
  <p>And for downloading I have</p>
  
  <pre><code>using (WebClient client = new WebClient())
  {
      string HtmlResult = String.Empty;
      FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteFile);
      request.Method = WebRequestMethods.Ftp.DownloadFile;
      request.EnableSsl = false;
      request.Credentials = new NetworkCredential(MyLogin, MyPassword);
      using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
      using (Stream responseStream = response.GetResponseStream())
      using (StreamReader reader = new StreamReader(responseStream))
      using (FileStream writer = new FileStream(localFilename, FileMode.Create))
      {
          long length = response.ContentLength;
          int bufferSize = 2048;
          int readCount;
          byte[] buffer = new byte[2048];
          readCount = responseStream.Read(buffer, 0, bufferSize);
          while (readCount &gt; 0)
          {
              writer.Write(buffer, 0, readCount);
              readCount = responseStream.Read(buffer, 0, bufferSize);
          }
      }
  }
  </code></pre>
  
  <p>2) Everything seems to work ... except when I try to unzip the downloaded ZIP file I get an invalid ZIP file.</p>