2012-01-12 47 views
6

我使用DotNetZip創建一個帶有內存字符串的zip存檔並使用以下代碼將其作爲附件下載。SharpZipLib使用內存字符串創建存檔並作爲附件下載

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是否支持以字節數組添加文件?

回答

14

試試下面

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

謝謝。這工作! – Dimuthu 2012-01-12 06:00:33

+0

所以一旦請求完成並且下載完成,內存是否釋放?我也在做一些非常相似的事情,可能會有很多文件。請求結束後,我需要清除內存。我很確定垃圾收集器會照顧它,但我不是100%確定的。 – harsimranb 2014-04-07 17:14:08

+0

垃圾收集器是想做的。但對於諸如「MemoryStream」之類的數據類型,您必須調用Dispose()或使用「using」語句來保證內存被釋放。 – 2014-04-08 03:37:02

相關問題