简体   繁体   English

内存流对象未保存到DotNetZip

[英]Memory stream objects are not saving to DotNetZip

I am trying to create a DotNetZip zip file that will be streamed to the user. 我正在尝试创建一个将流式传输给用户的DotNetZip zip文件。 Inside the zip file, I am inserting two memory streams. 在zip文件中,我插入了两个内存流。 But for some reason when I open the zip file, it is empty. 但由于某种原因,当我打开zip文件时,它是空的。 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. 我检查了msImage和msDoc的大小,它们都加载了数据,但msZip在大小方面显示的很少。 Not to mention that when it downloads, it is an empty zip file. 更不用说在下载时,它是一个空的zip文件。 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, 要求将msImage和msDoc设置回0位置,

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

Also requires that msZip be set to the 0 position. 还要求将msZip设置为0位置。 So by adding 所以加入

msZip.Seek(0, SeekOrigin.Begin);

just before the call to return the file, everything worked fine. 在调用返回文件之前,一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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