【问题标题】:SharpZipLib create an archive with an in-memory string and download as an attachmentSharpZipLib 使用内存中的字符串创建存档并作为附件下载
【发布时间】:2012-01-12 05:05:20
【问题描述】:

我使用 DotNetZip 创建一个带有内存字符串的 zip 存档,并使用以下代码将其作为附件下载。

byte[] formXml = UTF8Encoding.Default.GetBytes("<form><pkg>Test1</pkg></form>");
byte[] formHtml = UTF8Encoding.Default.GetBytes("<html><body>Test2</body></html>");

ZipFile zipFile = new ZipFile();
zipFile.AddEntry("Form.xml", formXml);
zipFile.AddEntry("Form.html", formHtml);
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("content-disposition", "attachment; filename=FormsPackage.zip");
zipFile.Save(Response.OutputStream); 
zipFile.Dispose();

现在我需要对 SharpZipLib 做同样的事情。我该怎么做 ? SharpZipLib 是否支持将文件添加为字节数组?

【问题讨论】:

    标签: c# asp.net sharpziplib


    【解决方案1】:

    试试下面

    MemoryStream msFormXml = new MemoryStream(UTF8Encoding.Default.GetBytes("<form><pkg>Test1</pkg></form>"));
    MemoryStream msFormHTML = new MemoryStream(UTF8Encoding.Default.GetBytes("<html><body>Test2</body></html>"));
    
    MemoryStream outputMemStream = new MemoryStream();
    ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
    
    zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
    
    ZipEntry xmlEntry = new ZipEntry("Form.xml");
    xmlEntry.DateTime = DateTime.Now;
     zipStream.PutNextEntry(xmlEntry);
    StreamUtils.Copy(msFormXml, zipStream, new byte[4096]);
    zipStream.CloseEntry();
    
    ZipEntry htmlEntry = new ZipEntry("Form.html");
    htmlEntry.DateTime = DateTime.Now;
    zipStream.PutNextEntry(htmlEntry);
    StreamUtils.Copy(msFormHTML, zipStream, new byte[4096]);
    zipStream.CloseEntry();
    
    zipStream.IsStreamOwner = false; 
    zipStream.Close(); 
    
    outputMemStream.Position = 0;
    
    byte[] byteArray = outputMemStream.ToArray();
    
    Response.Clear();
    Response.AppendHeader("Content-Disposition", "attachment; filename=FormsPackage.zip");
    Response.AppendHeader("Content-Length", byteArray.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.BinaryWrite(byteArray);
    

    【讨论】:

    • 那么一旦请求完成并且下载完成,内存是否被释放?我也在做一些非常相似的事情,可能有很多文件。我需要在请求完成后清除内存。我很确定垃圾收集器会处理它,但我不是 100% 确定。
    • 垃圾收集器应该这样做。但对于“MemoryStream”等数据类型,您必须调用 Dispose() 或使用“using”语句来保证内存被释放。
    • 只是想为其他人添加评论。如果不是同时添加所有流,StreamUtils.Copy 对我不起作用。我不得不选择 zipStream.Write(content, 0, content.length); (内容是文件流的字节[])否则很好的答案和upvote。
    • UTF8Encoding.Default.GetBytes 实际上是使用 .Net 的默认编码。如果你想强制 UTF8,你应该使用 Encoding.UTF8.GetBytes。
    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多