title: Download large files using a memorystream
body: <p>I'm writing a generic handler which is used to download rather large (400+ mb) files from a secured FTP server. I got my code working on small test images by copying the response stream to a MemoryStream and then binary write the bytes array.</p>
  
  <p>My code looks like this (DownloadFile.ashx):</p>
  
  <pre><code>// Set correct path
  string path = ftpHelper.GetCompletePath();
  path += "/" + loginId + "/" + folderName + "/" + fileName;
  
  FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
  request.UsePassive = false;
  request.Credentials = new NetworkCredential(ftpHelper.Username, ftpHelper.Password);
  
  byte[] fileBytes = null;
  
  using (var response = (FtpWebResponse)request.GetResponse())
  {
      using (Stream responseStream = response.GetResponseStream())
      {
          using (var memoryStream = new MemoryStream())
          {
              if (responseStream != null) responseStream.CopyTo(memoryStream);
              fileBytes = memoryStream.ToArray();
          }
      }
   }
  
  if (fileBytes.Length &gt; 0)
  {
       context.Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
       context.Response.BinaryWrite(fileBytes);
  }
  
  request.Abort();
  
  context.ApplicationInstance.CompleteRequest();
  </code></pre>
  
  <p>Question is: on a live webserver with 8gb of ram (it's currently using ~60% of it's existing ram since is quite a large website! It might need a ram upgrade ;-)) would it be safe to make the CopyTo() and use a MemoryStream with such large files?</p>
  
  <p>I know that I could just set the download link on the client directly to the FTP server by <a href="ftp://username%3apassword@path.com" rel="nofollow">ftp://username:password@path.com</a>, but the content on the FTP is password secured for a reason as there's some sensitive data on it.</p>
  
  <p>So, is a memorystream safe to use with such large files? And if not: is there any other way of doing this, that I have overlooked?</p>
  
  <p>Thanks in advance :-)</p>