从 byte[] 创建 zip 文件 [英] Create zip file from byte[]

查看:35
本文介绍了从 byte[] 创建 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a Zip file in .NET 4.5 (System.IO.Compression) from a series of byte arrays. As an example, from an API I am using I end up with a List<Attachment> and each Attachment has a property called Body which is a byte[]. How can I iterate over that list and create a zip file that contains each attachment?

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

Right now I am under the impression that I would have to write each attachment to disk and create the zip file from that.

//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 文件(存档):

After a little more playing around and reading I was able to figure this out. Here is how you can create a zip file (archive) with multiple files without writing any temporary data to disk:

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" };
}

这篇关于从 byte[] 创建 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆