.NET Core创建内存中的Zip文件

26

我正在处理一个MVC项目,在其中创建动态pdf文件(使用wkhtmltopdf),我希望将它们返回到zip文件中。 pdf文件是实时生成的 - 我不需要存储它们,所以我的代码来返回一个单独的文件是:

File(pdfBytes, "application/pdf", "file_name")

浏览一下Microsoft文档,他们的示例演示了如何处理存储的文件:

 string startPath = @"c:\example\start";
 string zipPath = @"c:\example\result.zip";
 string extractPath = @"c:\example\extract";

 ZipFile.CreateFromDirectory(startPath, zipPath);
 ZipFile.ExtractToDirectory(zipPath, extractPath);
在我的情况下,我想创建 N 个 pdf 文件,并将其作为 zip 文件返回给视图。就像这样:
ZipFile zip = new ZipFile();
foreach(var html in foundRawHTML)
{
//create pdf

//append pdf to zip
}

return zip;

尽管这是不可行的,因为:

  1. ZipFile和File是静态的,无法实例化
  2. 没有办法在飞行中(在内存中)将文件添加到zip文件中

欢迎任何帮助

1个回答

55

您可以使用System.IO.Compression中的内存字节数组和ZipArchive,无需映射本地驱动器:

    public static byte[] GetZipArchive(List<InMemoryFile> files)
        {
            byte[] archiveFile;
            using (var archiveStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
                {
                    foreach (var file in files)
                    {
                        var zipArchiveEntry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
                        using (var zipStream = zipArchiveEntry.Open())
                            zipStream.Write(file.Content, 0, file.Content.Length);
                    }
                }

                archiveFile = archiveStream.ToArray();
            }

            return archiveFile;
        }

public class InMemoryFile
    {
        public string FileName { get; set; }
        public byte[] Content { get; set; }
    }

任何想要简化使用情况的人,也不要尝试!如果你这样做会导致一个无效的zip文件。直接使用此代码,一切都会正常。 - minimalist_zero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接