是的,完全可以在内存中创建zip文件,在这里使用SharpZip
库进行示例(更新:在末尾添加了一个使用ZipArchive
的示例):
public static void Main()
{
var fileContent = Encoding.UTF8.GetBytes(
@"{
""fruit"":""apple"",
""taste"":""yummy""
}"
);
var zipStream = new MemoryStream();
var zip = new ZipOutputStream(zipStream);
AddEntry("file0.json", fileContent, zip);
AddEntry("file1.json", fileContent, zip);
zip.Close();
File.WriteAllBytes("test.zip", zipStream.ToArray());
}
private static void AddEntry(string fileName, byte[] fileContent, ZipOutputStream zip)
{
var zipEntry = new ZipEntry(fileName) {DateTime = DateTime.Now, Size = fileContent.Length};
zip.PutNextEntry(zipEntry);
zip.Write(fileContent, 0, fileContent.Length);
zip.CloseEntry();
}
您可以使用Nuget命令PM> Install-Package SharpZipLib
获取SharpZip
。
更新:
注意:我更喜欢使用 .NET Framework 库(而不是外部库)来实现此目的
这里是一个使用内置的System.IO.Compression.Dll
中的ZipArchive
的示例。
public static void Main()
{
var fileContent = Encoding.UTF8.GetBytes(
@"{
""fruit"":""apple"",
""taste"":""yummy""
}"
);
var zipContent = new MemoryStream();
var archive = new ZipArchive(zipContent, ZipArchiveMode.Create);
AddEntry("file1.json",fileContent,archive);
AddEntry("file2.json",fileContent,archive);
archive.Dispose();
File.WriteAllBytes("testa.zip",zipContent.ToArray());
}
private static void AddEntry(string fileName, byte[] fileContent,ZipArchive archive)
{
var entry = archive.CreateEntry(fileName);
using (var stream = entry.Open())
stream.Write(fileContent, 0, fileContent.Length);
}