DotNetZip从MemoryStream打开zip文件



我喜欢做的不是在磁盘上存储zip文件,而是从MemoryStream打开它。

我正在查看DotNetZip编程示例的文档:请注意,我根据我认为可能需要的内容对其进行了轻微调整。

var ms = new MemoryStream();
using (ZipFile zip = new ZipFile())
{
zip.AddFile("ReadMe.txt");
zip.AddFile("7440-N49th.png");
zip.AddFile("2008_Annual_Report.pdf");        
zip.Save(ms); // this will save the files in memory steam
}

// now what I need is for the zip file to open up so that 
the user can view all the files in it. Not sure what to do next after 
zip.Save(ms) for this to happen. 

试试这个:

public ActionResult Index()
{
var memoryStream = new MemoryStream();
using (var zip = new ZipFile())
{
zip.AddFile("ReadMe.txt");
zip.AddFile("7440-N49th.png");
zip.AddFile("2008_Annual_Report.pdf"); 
zip.Save(memoryStream);
}
memoryStream.Seek(0, 0);
return File(memoryStream, "application/octet-stream", "archive.zip");
}

如果这是本地的。您需要将流保存到文件中,并在其中调用Process.Start

如果这是在服务器上。只需使用适当的mime类型将ms写入Response即可。

您必须将内存流的内容作为响应发送回:

using (MemoryStream ms = new MemoryStream())
{
using (ZipFile zip = new ZipFile())
{
zip.AddFile("ReadMe.txt");
zip.AddFile("7440-N49th.png");
zip.AddFile("2008_Annual_Report.pdf");        
zip.Save(ms); // this will save the files in memory steam
}
context.Response.ContentType = "application/zip";
context.Response.AddHeader("Content-Length", ms.Size);
context.Response.AddHeader("Content-disposition", "attachment; filename=MyZipFile.zip");
ms.Seek(0, SeekOrigin.Begin);
ms.WriteTo(context.Response.OutputStream);
}

尝试创建一个ActionResult,如下所示:我不能100%确定var fileData = ms;这一行,而且我现在还没有访问开发环境的权限,但应该有足够的资源让您解决它。

public ActionResult DownloadZip()
{
using (MemoryStream ms = new MemoryStream())
{
using (ZipFile zip = new ZipFile())
{
zip.AddFile("ReadMe.txt");
zip.AddFile("7440-N49th.png");
zip.AddFile("2008_Annual_Report.pdf");        
zip.Save(ms); // this will save the files in memory steam
}
byte[] fileData = ms.GetBuffer();// I think this will work. Last time I did it, I did something like this instead... Zip.CreateZip("LogPosts.csv", System.Text.Encoding.UTF8.GetBytes(csv));
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "Whatever.zip",
// always prompt the user for downloading, set to true if you want 
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, "application/octet-stream");
}
}

通过这种方式,我们可以将zip写入输出流。可能有助于

ZipFile zip = new ZipFile();
List<Attachment> listattachments = email.Attachments;
int acount = attachments.Count;
for (int i = 0; i < acount; i++)
{
zip.AddEntry(attachments[i].FileName, listattachments[i].Content);
}
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("{0}.zip", message.Headers.From.DisplayName);
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();     

最新更新