在c#.net中更新zip时出现内存不足异常

use*_*550 6 .net c# out-of-memory

我在尝试在c#.net中的Zip文件中添加文件时遇到OutofMemoryException.我使用32位架构来构建和运行应用程序

            string[] filePaths = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\capture\\capture");
            System.IO.Compression.ZipArchive zip = ZipFile.Open(filePaths1[c], ZipArchiveMode.Update);

                foreach (String filePath in filePaths)

                {
                    string nm = Path.GetFileName(filePath);
                    zip.CreateEntryFromFile(filePath, "capture/" + nm, CompressionLevel.Optimal);
                }
                zip.Dispose();
                zip = null;
Run Code Online (Sandbox Code Playgroud)

我无法理解它背后的共鸣

Pet*_*iho 9

确切的原因取决于各种因素,但很可能只是简单地向存档添加太多.请尝试使用该ZipArchiveMode.Create选项,将存档直接写入磁盘而不将其缓存在内存中.

如果您真的想要更新现有存档,您仍然可以使用ZipArchiveMode.Create.但它需要打开现有存档,将其所有内容复制到新存档(使用Create),然后添加新内容.

如果没有一个好的,最小的,完整的代码示例,就不可能确定异常来自何处,更不用说如何修复它.

编辑:

这就是我所说的"...打开现有存档,将其所有内容复制到新存档(使用Create),然后添加新内容":

string[] filePaths = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\capture\\capture");

using (ZipArchive zipFrom = ZipFile.Open(filePaths1[c], ZipArchiveMode.Read))
using (ZipArchive zipTo = ZipFile.Open(filePaths1[c] + ".tmp", ZipArchiveMode.Create))
{
    foreach (ZipArchiveEntry entryFrom in zipFrom.Entries)
    {
        ZipArchiveEntry entryTo = zipTo.CreateEntry(entryFrom.FullName);

        using (Stream streamFrom = entryFrom.Open())
        using (Stream streamTo = entryTo.Open())
        {
            streamFrom.CopyTo(streamTo);
        }
    }

    foreach (String filePath in filePaths)
    {
        string nm = Path.GetFileName(filePath);
        zipTo.CreateEntryFromFile(filePath, "capture/" + nm, CompressionLevel.Optimal);
    }
}

File.Delete(filePaths1[c]);
File.Move(filePaths1[c] + ".tmp", filePaths1[c]);
Run Code Online (Sandbox Code Playgroud)

或类似的东西.缺乏一个好的,最小的,完整的代码示例,我只是在浏览器中编写了上述内容.我没有尝试编译它,没关系测试它.您可能想要调整一些细节(例如临时文件的处理).但希望你能得到这个想法.

  • 正如有关更新/创建选项所述,[Microsoft 文档](https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchivemode(v=vs.110).aspx) 指出:“当模式设置为Update时,底层文件或流必须支持读、写和查找,整个归档文件的内容保存在内存中,在归档文件被释放之前,不会向底层文件或流写入任何数据。 ” 只需将其添加到此处即可轻松找到官方信息。 (2认同)