在C#中添加多个文件到内存中的zip归档 [英] Adding multiple files to an in memory zip archive in c#

查看:136
本文介绍了在C#中添加多个文件到内存中的zip归档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Zip文件库.NET 4.5一堆的byte []附件的内存中创建一个.zip文件:

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:

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是一个byte []数据和字符串文件名的一类。

PdfAttachment is a class with a byte[] Data and string Filename.

我的问题是双重的。有一次,zip压缩包是空的。 2,而不是将其保存到一个文件,我想使用的响应输出下载的文件在用户浏览器,这是我与尝试:

My problem is twofold. Once, the zip archive is empty. 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:

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.

推荐答案

FILESTREAM 不会被写入,因为它不与归档相关的。

The fileStream is never written to because it is not associated with the archive.

所以存档被写入的MemoryStream

的BinaryWrite 只接受字节[] 所以使用 memoryStream.ToArray()

此外, Response.ContentType 值是错误的。

这篇关于在C#中添加多个文件到内存中的zip归档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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