是的,可以完全在内存中创建一个 zip 文件,这里是一个使用 SharpZip 库的示例(更新:最后添加了一个使用 ZipArchive 的示例): p>
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); //first file
AddEntry("file1.json", fileContent, zip); //second file (with same content)
zip.Close();
//only for testing to see if the zip file is valid!
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 框架库(相对于外部库)来完成此操作
这是一个使用来自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); //second file (same content)
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);
}