Memory stream objects are not saved in DotNetZip
I am trying to create a DotNetZip zip file that will be passed to the user. Inside the zip file, I insert two memory streams. But for some reason, when I open the zip file, it is empty. I looked through the documentation and didn't find anything useful. My code:
public async Task<FileResult> DownloadFile(string fileName){
//Create image memory stream
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath("~/Images/" + fileName));
MemoryStream msImage = new MemoryStream();
image.Save(msImage, image.RawFormat);
//Create Word document using DocX
MemoryStream msDoc = new MemoryStream();
DocX doc = DocX.Create(msDoc);
Paragraph p1 = doc.InsertParagraph();
p1.AppendLine("Text information...");
Paragraph p2 = doc.InsertParagraph();
p2.AppendLine("DISCLAIMER: ...");
doc.SaveAs(msDoc);
//Create Zip File and stream it to the user
MemoryStream msZip = new MemoryStream();
ZipFile zip = new ZipFile();
msImage.Seek(0, SeekOrigin.Begin);
msDoc.Seek(0, SeekOrigin.Begin);
ZipEntry imageEntry = zip.AddEntry("MyImageName.jpg", msImage);
ZipEntry docEntry = zip.AddEntry("MyWordDocName.docx", msDoc);
zip.Save(msZip);
image.Dispose();
doc.Dispose();
zip.Dispose();
return File(msZip, System.Net.Mime.MediaTypeNames.Application.Octet, "MyZipFileName.zip");
}
I checked the size of both msImage and msDoc and they are both loaded with data, but msZip shows very little in terms of size. Not to mention, it is a blank zip file on upload. I need to know why these streams are not being added. Thanks a million!
+3
source to share
1 answer
Ok ... found the answer myself ....
So, as it turned out, not only
ZipEntry imageEntry = zip.AddEntry("MyImageName.jpg", msImage);
ZipEntry docEntry = zip.AddEntry("MyWordDocName.docx", msDoc);
requires msImage and msDoc to be returned to position 0,
return File(msZip, System.Net.Mime.MediaTypeNames.Application.Octet, "MyZipFileName.zip");
It also requires msZip to be set to position 0. So by adding
msZip.Seek(0, SeekOrigin.Begin);
before calling to return a file everything worked fine.
+5
source to share