内存流对象未保存到DotNetZip

时间:2014-08-07 22:11:15

标签: c# asp.net-mvc dotnetzip

我正在尝试创建一个将流式传输给用户的DotNetZip zip文件。在zip文件中,我插入了两个内存流。但由于某种原因,当我打开zip文件时,它是空的。我查看了文档,发现几乎没有任何帮助。我的代码:

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");
}

我已经检查了msImage和msDoc的大小,并且它们都加载了数据,但msZip在大小方面显示的很少。更不用说在下载时,它是一个空的zip文件。我需要知道为什么没有添加这些流。万分感谢!

1 个答案:

答案 0 :(得分:6)

好的......我自己找到了答案......

事实证明,不仅

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

要求将msImage和msDoc设置回0位置,

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

还要求将msZip设置为0位置。所以加入

msZip.Seek(0, SeekOrigin.Begin);

在调用返回文件之前,一切正常。