Search code examples
c#compressionout-of-memoryc#-ziparchive

How to fix or get around a system out of memory exception when zipping large files?


So I have a application that zips directories and it works perfectly except that today I got an exception and when I checked the log it turned out that it got a system out of memory exception because of this directory that is ~550mb. So my question is: Is there a way to get around this or enable my application to work with bigger sized directories?

Here is the code that zips the directories:

using (FileStream zipToOpen = new FileStream(destdir1, FileMode.Open))
{
   using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
    {
      int ind = folder.LastIndexOf("\\") + 1;
      string folderName = folder.Substring(ind, folder.Length - ind);

      ZipArchiveEntry readmeEntry;
      DirectoryInfo d = new DirectoryInfo(folder);
      FileInfo[] Files = d.GetFiles("*");
      foreach (FileInfo file in Files)
      {
        readmeEntry = archive.CreateEntryFromFile(folder + "\\" + file.Name, folderName + "/" + file.Name);
      }
      DeleteDirectory(folder);
      }
}

Solution

  • It sounds like a limitation of the ZipArchive library, which probably stores all temporary data in memory when zipping.

    It might not be possible to solve the problem of excessive memory usage, but to work around the issue you could rebuild the application in 64 bit mode. This will probably remove the memory ceiling you're experiencing.