我想用 C# 创建一个包含将近 8 GB 数据的 zip 文件。我正在使用以下代码:
using (var zipStream = new ZipOutputStream(System.IO.File.Create(outPath)))
{
zipStream.SetLevel(9); // 0-9, 9 being the highest level of compression
var buffer = new byte[1024*1024];
foreach (var file in filenames)
{
var entry = new ZipEntry(Path.GetFileName(file)) { DateTime = DateTime.Now };
zipStream.PutNextEntry(entry);
var bufferSize = BufferedSize;
using (var fs = new BufferedStream(System.IO.File.OpenRead(file), bufferSize))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
zipStream.Finish();
zipStream.Close();
}
此代码适用于 1 GB 以下的小文件,但当数据达到 7-8 GB 时会引发异常。