gpt4 book ai didi

c# - 从 byte[] 创建 zip 文件

转载 作者:IT王子 更新时间:2023-10-29 03:53:10 26 4
gpt4 key购买 nike

我正在尝试通过一系列字节数组在 .NET 4.5 (System.IO.Compression) 中创建一个 Zip 文件。例如,从我正在使用的 API 中,我最终得到一个 List<Attachment>每个 Attachment有一个名为 Body 的属性这是 byte[] .我如何遍历该列表并创建一个包含每个附件的 zip 文件?

现在我的印象是我必须将每个附件写入磁盘并从中创建 zip 文件。

//This is great if I had the files on disk
ZipFile.CreateFromDirectory(startPath, zipPath);
//How can I create it from a series of byte arrays?

最佳答案

经过更多的尝试和阅读,我终于弄明白了。以下是如何在不将任何临时数据写入磁盘的情况下创建包含多个文件的 zip 文件(存档):

using (var compressedFileStream = new MemoryStream())
{
//Create an archive and store the stream in memory.
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, false)) {
foreach (var caseAttachmentModel in caseAttachmentModels) {
//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Name);

//Get the stream of the attachment
using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body))
using (var zipEntryStream = zipEntry.Open()) {
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
}
}

return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
}

关于c# - 从 byte[] 创建 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com