c# – SharpZipLib创建一个带有内存字符串的存档,并作为附件下载

前端之家收集整理的这篇文章主要介绍了c# – SharpZipLib创建一个带有内存字符串的存档,并作为附件下载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用DotNetZip创建一个带有内存字符串的zip存档,并使用以下代码将其下载为附件.
  1. byte[] formXml = UTF8Encoding.Default.GetBytes("<form><pkg>Test1</pkg></form>");
  2. byte[] formHtml = UTF8Encoding.Default.GetBytes("<html><body>Test2</body></html>");
  3.  
  4. ZipFile zipFile = new ZipFile();
  5. zipFile.AddEntry("Form.xml",formXml);
  6. zipFile.AddEntry("Form.html",formHtml);
  7. Response.ClearContent();
  8. Response.ClearHeaders();
  9. Response.AppendHeader("content-disposition","attachment; filename=FormsPackage.zip");
  10. zipFile.Save(Response.OutputStream);
  11. zipFile.Dispose();

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

解决方法

试试以下
  1. MemoryStream msFormXml = new MemoryStream(UTF8Encoding.Default.GetBytes("<form><pkg>Test1</pkg></form>"));
  2. MemoryStream msFormHTML = new MemoryStream(UTF8Encoding.Default.GetBytes("<html><body>Test2</body></html>"));
  3.  
  4. MemoryStream outputMemStream = new MemoryStream();
  5. ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
  6.  
  7. zipStream.SetLevel(3); //0-9,9 being the highest level of compression
  8.  
  9. ZipEntry xmlEntry = new ZipEntry("Form.xml");
  10. xmlEntry.DateTime = DateTime.Now;
  11. zipStream.PutNextEntry(xmlEntry);
  12. StreamUtils.Copy(msFormXml,zipStream,new byte[4096]);
  13. zipStream.CloseEntry();
  14.  
  15. ZipEntry htmlEntry = new ZipEntry("Form.html");
  16. htmlEntry.DateTime = DateTime.Now;
  17. zipStream.PutNextEntry(htmlEntry);
  18. StreamUtils.Copy(msFormHTML,new byte[4096]);
  19. zipStream.CloseEntry();
  20.  
  21. zipStream.IsStreamOwner = false;
  22. zipStream.Close();
  23.  
  24. outputMemStream.Position = 0;
  25.  
  26. byte[] byteArray = outputMemStream.ToArray();
  27.  
  28. Response.Clear();
  29. Response.AppendHeader("Content-Disposition","attachment; filename=FormsPackage.zip");
  30. Response.AppendHeader("Content-Length",byteArray.Length.ToString());
  31. Response.ContentType = "application/octet-stream";
  32. Response.BinaryWrite(byteArray);

猜你在找的C#相关文章