title: Downloading files as a zip result in corrupted zips in ASP.NET MVC
body: <p>I have a server hosting a large XML file archive and an API retrieves requested files inside a zip.  If I select around 11 or less files, the zip returns just fine.  If I retrieve more, I receive the following error when attempting to open the zip:</p>
  
  <blockquote>
    <p>"Windows cannot open the folder. The Compressed (zipped) Folder is
    invalid."</p>
  </blockquote>
  
  <p>Here are the data classes and methods to create the zip:</p>
  
  <pre><code>//Archive file containing filename and content as memory stream
  public class ArchiveFile {
      public string FileName;
      public System.IO.MemoryStream FileContent;
  }
  
  //Method to retrieve archive files and zip them
  public static System.IO.MemoryStream GetFilesAsZip (string[] arrFileNames) {
      MemoryStream zipStream  = null;
      using (zipStream = new MemoryStream()) {
          // Retrieve files using above method
          ArchiveFile[] retrievedFiles = GetFilesFromArchive(arrFileNames);
          // Initialize new ZipArchive on the return object's MemoryStream property
          using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Update, leaveOpen: true)) {
              // Write file entries into archive
              foreach (ArchiveFile dataFile in retrievedFiles) {
                  if (dataFile.FileContent != null) {
                      // Create new ZipArchiveEntry with content
                      ZipArchiveEntry zipEntry = archive.CreateEntry(dataFile.FileName);
                      dataFile.FileContent.WriteTo(zipEntry.Open());
                  }//end if
              } // end foreach
          } //end using
      } //end using
      return zipStream;
  }//end method
  
  //API to return content to user as an MVC File Content Result
  [HttpGet]
  public ActionResult DownloadFiles (string [] fileNames) {
      FileContentResult data = new FileContentResult(GetFiles(fileNames).GetBuffer(), “application/zip”) { FileDownloadName = “files.zip” };
      return data;
  } //end method
  </code></pre>
  
  <p>The corruption may have something to do with space allocation when writing to the memory stream. I noticed all my "successful" zips (11 or less files) were of size 259 KB but all "unsuccessful" zips (more than 11 files) were of size 517 KB, with some larger attempted zips of size 1034 KB. It strikes me as too much of a coincidence that these are all multiples of 258.5 KB, especially since a zip of 11 files results in a 259 KB zip but a zip of 12 files results in a 517 KB zip. </p>
  
  <p>Any insight on what it could be?</p>