0

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.

e-zero
  • 355
  • 3
  • 9
  • 17
  • 1
    only thing that sticks out, is you're closing the `docMS` before closing the zip stream. Close the zip stream first, then close the document stream. It looks like you clobbered the zip entry. Did you actually debug it? – t0mm13b Nov 29 '16 at 00:39
  • So I put zipStream.CloseEntry() before docMS.close() but it still does not work. I'm not sure what you mean by 'clobbered the zip entry'? – e-zero Nov 29 '16 at 00:54

0 Answers0