【问题标题】:How to create ZipArchive from files in memory in C#?如何在 C# 中从内存中的文件创建 ZipArchive?
【发布时间】:2015-06-21 06:10:15
【问题描述】:

是否有可能从内存中的文件(而不是实际上在磁盘上)创建一个 ZipArchive。

以下是用例:IEnumerable<HttpPostedFileBase> 变量中接收到多个文件。我想使用ZipArchive 将所有这些文件压缩在一起。问题是ZipArchive 只允许CreateEntryFromFile,它需要文件的路径,因为我只有内存中的文件。

问题: 有没有办法使用“流”在ZipArchive 中创建“条目”,以便我可以直接将文件的内容放入 zip 中?

我不想先保存文件,创建 zip(从保存的文件的路径),然后删除单个文件。

这里,attachmentFilesIEnumerable<HttpPostedFileBase>

using (var ms = new MemoryStream())
{
    using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        foreach (var attachment in attachmentFiles)
        {
            zipArchive.CreateEntryFromFile(Path.GetFullPath(attachment.FileName), Path.GetFileName(attachment.FileName),
                                CompressionLevel.Fastest);
        }
    }
    ...
}

【问题讨论】:

  • 为什么不创建一个临时文件,然后在存档完成后发布?
  • 如果可能的话,我想避免创建临时文件并在之后删除它。这就是我在问题中写的,但如果没有其他办法,那么我将不得不这样做。

标签: c# .net zip zipfile


【解决方案1】:

首先感谢@Alex 的完美回答。
同样对于您需要从文件系统读取的场景:

using (var ms = new MemoryStream())
{
    using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        foreach (var file in filesAddress)
        {
            zipArchive.CreateEntryFromFile(file, Path.GetFileName(file));
        }
    }

    ...
}

System.IO.Compression.ZipFileExtensions的帮助下

【讨论】:

    【解决方案2】:

    是的,您可以使用 @AngeloReis 在 cmets 中指出的 ZipArchive.CreateEntry 方法来执行此操作,并针对稍微不同的问题描述了 here

    您的代码将如下所示:

    using (var ms = new MemoryStream())
    {
        using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
        {
            foreach (var attachment in attachmentFiles)
            {
                var entry = zipArchive.CreateEntry(attachment.FileName, CompressionLevel.Fastest);
                using (var entryStream = entry.Open())
                {
                    attachment.InputStream.CopyTo(entryStream);
                }
            }
        }
        ...
    }
    

    【讨论】:

    • 工作就像一个魅力,谢谢!我用它创建了一堆我在数据库中存储为 byte[] 的 PDF 的 zip 文件。根本不需要涉及文件系统。用户单击一个按钮,然后通过他们的 Web 浏览器下载 .zip 文件。 (顺便说一句,在最里面的“使用”块上,我改为使用 entryStream.Write(arrBytes, 0, arrBytes.Length);
    • 附件文件是什么?
    • 我必须在末尾添加ms.Seek(0, SeekOrigin.Begin); 才能使用它。
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多