I am trying to zip a Word document that is stored in a MemoryStream like this:
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();
When the zip file is downloaded and unzipped, 'my_document.docx' opens up as a blank document. If I modify the code above so that the 'my_document.docx' file is downloaded directly (not zipped) via the MemoryStream 'docMS', then the document opens up fine. I cannot figure out why.