c# - SharpZipLib 使用内存中的字符串创建存档并作为附件下载

标签 c# asp.net sharpziplib

我使用 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 是否支持将文件添加为字节数组?

最佳答案

试试下面

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);

关于c# - SharpZipLib 使用内存中的字符串创建存档并作为附件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830386/

相关文章:

c# - 使用静态类型语言 (F#) 处理异构数据

c# - Entity Framework 4 DB-First 依赖注入(inject)?

silverlight - 如何在 Windows Phone 7 中解压 zip 文件?

c# - ICSharpCode.SharpZipLib 验证 zip 文件

asp.net - 在数据库表中存储字节数组的最节省空间的方法 - ASP.NET

c# - 选项卡索引处理 - ASP.NET MVC 表单控件

c# - Tidekit 和 C#/Java/C++ native 代码兼容性

c# - 正确获取泛型类的泛型类的约束

c# - asp.net 从查询中获取数据

javascript - 如何在回发时保持 SlideToggle 的状态?