简体   繁体   English

在C#中将多个文件添加到内存中的zip存档中

[英]Adding multiple files to an in memory zip archive in c#

I'm trying to use the Zip Archive library in .NET 4.5 to create a .zip file in memory of a bunch of byte[] attachments: 我正在尝试使用.NET 4.5中的Zip存档库在一堆byte []附件的内存中创建一个.zip文件:

using (var memoryStream = new MemoryStream())
{
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        string zipFilename = string.Format(@"c:\temp\{0} - {1}.zip",
            "test",
            System.DateTime.Now.ToString("yyyyMMddHHmm"));
        using (var fileStream = new FileStream(zipFilename, FileMode.Create))
        {
            foreach (var attachment in attachments)
            {
                ZipArchiveEntry entry = archive.CreateEntry(attachment.FileName);

                using (Stream ZipFile = entry.Open())
                {
                    byte[] data = attachment.Data;
                    ZipFile.Write(data, 0, data.Length);
                }
            }
        }

    }
}

PdfAttachment is a class with a byte[] Data and string Filename. PdfAttachment是一个带有byte []数据和字符串Filename的类。

My problem is twofold. 我的问题是双重的。 Once, the zip archive is empty. 一次,zip存档为空。 2, rather than save it to a file, I'd like to use the response outputs to download the file in the users browser, which I have tried with: 2,而不是将其保存到文件中,我想使用响应输出在用户浏览器中下载该文件,我已经尝试过:

Response.Clear();

Response.ClearContent();
Response.ClearHeaders();

Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.zip; size={1}", "test.zip", memoryStream.Length));
Response.BinaryWrite(memoryStream);

Response.Flush();
Response.End();

I haven't been able to find many examples online, hence the vagueness. 我在网上找不到很多示例,因此含糊不清。

The fileStream is never written to because it is not associated with the archive. 永远不会写入fileStream ,因为它与存档没有关联。

So the archive is being written to the memoryStream . 因此,存档文件正在写入memoryStream

BinaryWrite only accepts a byte[] so use memoryStream.ToArray() . BinaryWrite仅接受byte[]因此请使用memoryStream.ToArray()

Also, Response.ContentType value is wrong. 另外, Response.ContentType值是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM