C#OutOfMemoryException使用SharpZipLib创建ZipOutputStream [英] C# OutOfMemoryException creating ZipOutputStream using SharpZipLib
问题描述
在下面的代码中,我总是收到一个非常烦人的OutOfMemory异常.
I keep getting a very annoying OutOfMemory exception on the following code.
我正在压缩很多小文件(PDF,每个文件大约1.5mb).
I'm zipping a lot of small files (PDF, each being 1.5mb approx).
起初,压缩25个文件后,我得到了例外,这似乎不是一个庞大的归档文件.
At first I was getting the exception afer 25 files zipped, which doesn't seem like a massing archive.
设置ZipEntry的大小有所帮助,因为现在我设法压缩多达110个文件(我正在Visual Studio中进行调试)
Setting up the size of the ZipEntry somehow helped since now I manage to get up to 110 files zipped (I'm debugging under visual studio)
这是我的代码,也许有问题.
Here's my code, maybe there's something wrong with it.
任何帮助将不胜感激.
谢谢
public static MemoryStream Zip(Dictionary<string, byte[]> files)
{
var outputMemStream = new MemoryStream();
var zipStream = new ZipOutputStream(outputMemStream);
zipStream.SetLevel(9);
foreach (var file in files)
{
zipStream.PutNextEntry(new ZipEntry(file.Key.FmtValidFileName())
{
Size = file.Value.Length
});
zipStream.Write(file.Value, 0, file.Value.Length);
zipStream.Flush();
}
zipStream.Finish();
outputMemStream.Position = 0;
return outputMemStream;
}
推荐答案
即使在内存为16gb的64位系统上,我本来也很安全,但我还是放弃了使用MemoryStream的尝试.
I gave up trying to use MemoryStream even though being on a 64bit system with 16gb of memory I should have been safe on that side.
我发现的相关主题是: OutOfMemoryException,同时填充了MemoryStream :在16GB系统上分配256MB
The relevant topic I found was: OutOfMemoryException while populating MemoryStream: 256MB allocation on 16GB system
并使用一个临时文件而不是内存来写入/读取数据.
And using a temporary file to write/read the data instead of memory.
这篇关于C#OutOfMemoryException使用SharpZipLib创建ZipOutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!