我正在try 从一系列字节数组创建.NET4.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" };
}

.net相关问答推荐

无法在 Blazor Server 应用程序中触发 InputRadio 的 onchange 事件

使用 DataDog 收集 OpenTelemetry 跟踪

等待时 Blazor 服务器按钮刷新

从 Contentful 中的富文本元素中获取价值?

为什么解码后的字节数组与原始字节数组不同?

如何规范机器之间连字符的排序顺序?

将 DataRowCollection 转换为 IEnumerable

如何授予所有用户对我的应用程序创建的文件的完全权限?

.NET 事件 - 什么是对象发送者和 EventArgs e?

Visual Studio 2017 和 2019 突出显示滚动条中所选单词的出现

String.Replace() 与 StringBuilder.Replace()

如何使用 C# 创建自签名证书?

判断 .NET 中的目录和文件写入权限

什么是 .NET 应用程序域?

为什么 Roslyn 中有异步状态机类(而不是 struct )?

IEnumerable vs IReadonlyCollection vs ReadonlyCollection 用于公开列表成员

如何将 MailMessage 对象作为 *.eml 或 *.msg 文件保存到磁盘

绑定在代码隐藏中定义的对象

如何在 C# 中使用迭代器反向读取文本文件

您可以将 Microsoft Entity Framework 与 Oracle 一起使用吗?