简体   繁体   中英

Memory stream objects are not saving to DotNetZip

I am trying to create a DotNetZip zip file that will be streamed to the user. Inside the zip file, I am inserting two memory streams. But for some reason when I open the zip file, it is empty. I have looked through the documentation and found little to nothing helpful. 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 have 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 that when it downloads, it is an empty zip file. I need to know why these streams are not being added. Thanks a million!

Ok... found the answer myself....

So as it turns out, not only does

ZipEntry imageEntry = zip.AddEntry("MyImageName.jpg", msImage);
ZipEntry docEntry = zip.AddEntry("MyWordDocName.docx", msDoc);

require that msImage and msDoc be set back to the 0 position,

return File(msZip, System.Net.Mime.MediaTypeNames.Application.Octet, "MyZipFileName.zip");

Also requires that msZip be set to the 0 position. So by adding

msZip.Seek(0, SeekOrigin.Begin);

just before the call to return the file, everything worked fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM