Out of memory exception while updating zip in c#.net

前端 未结 2 817
萌比男神i
萌比男神i 2020-12-06 18:46

I am getting OutofMemoryException While trying to add files in Zip file in c#.net. I am using 32bit architecture for bulding and running application

string[]          


        
2条回答
  •  执念已碎
    2020-12-06 19:00

    The reason is simple. OutOfMemoryException means memory is not enough for the execution.

    Compression consumes a lot of memory. There is no guarantee that a change of logic can solve the problem. But you can consider different methods to alleviate it.

    1. Since your main program must be 32-bit, you can consider starting another 64-bit process to do the compression (use System.Diagnostics.Process.Start). After the 64-bit process finishes its job and exits, your 32-bit main program can continue. You can simply use a tool already installed on the system, or write a simple program yourself.

    2. Another method is to dispose each time you add an entry. ZipArchive.Dispose saves the file. After each iteration, memory allocated for the ZipArchive can be freed.

    foreach (String filePath in filePaths)
    {
        System.IO.Compression.ZipArchive zip = ZipFile.Open(filePaths1[c], ZipArchiveMode.Update);
        string nm = Path.GetFileName(filePath);
        zip.CreateEntryFromFile(filePath, "capture/" + nm, CompressionLevel.Optimal);
        zip.Dispose();
    }
    

    This approach is not straightforward, and it might not be as effective as the first approach.

提交回复
热议问题