在内存中编写 Zip 文件
以下示例将返回包含提供给它的文件的压缩文件的 byte[]
数据,而无需访问文件系统。
public static byte[] ZipFiles(Dictionary<string, byte[]> files)
{
using (MemoryStream ms = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Update))
{
foreach (var file in files)
{
ZipArchiveEntry orderEntry = archive.CreateEntry(file.Key); //create a file with this name
using (BinaryWriter writer = new BinaryWriter(orderEntry.Open()))
{
writer.Write(file.Value); //write the binary data
}
}
}
//ZipArchive must be disposed before the MemoryStream has data
return ms.ToArray();
}
}