我正在尝试压缩存储在MemoryStream中的Word文档,如下所示:
MemoryStream outputMemStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
ZipEntry newEntry = new ZipEntry("my_document.docx");
newEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(newEntry);
//docMS is a MemoryStream that contains a Word document
StreamUtils.Copy(docMS, zipStream, new byte[4096]);
docMS.Close();
zipStream.CloseEntry();
zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.
zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream.
outputMemStream.Position = 0;
context.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "my_document.zip"));
context.Response.ContentType = "application/octet-stream";
zipStream.WriteTo(context.Response.OutputStream);
context.Response.End();
下载并解压缩zip文件后,“my_document.docx”将打开为空白文档。如果我修改上面的代码,以便通过MemoryStream“docMS”直接下载(而不是压缩)'my_document.docx'文件,那么文档就可以正常打开。我无法弄清楚原因。