如何从MemoryStream打开一个zip文件

时间:2012-12-17 21:18:03

标签: c# dotnetzip

我正在使用DotNetZip。

我需要做的是打开包含服务器文件的zip文件。 然后,用户可以抓取文件并将其本地存储在他们的计算机上。

我之前做的是以下内容:

      string path = "Q:\\ZipFiles\\zip" + npnum + ".zip";
      zip.Save(path);
      Process.Start(path);

请注意,Q:是服务器上的驱动器。使用Process.Start,它只需打开zip文件,以便用户可以访问所有文件。我喜欢这样做,但不是将文件存储在磁盘上,而是从内存中显示它。

现在,我不想将zip文件存储在服务器上,而是喜欢用MemoryStream打开它

我有以下但似乎无法正常工作

      var ms = new MemoryStream();
      zip.Save(ms);

但不确定如何在从内存流中打开zip文件方面继续进行,以便用户可以访问所有文件

3 个答案:

答案 0 :(得分:1)

这是一段实时的代码(复制的逐字),我写这篇文章是为了将一系列博客文章下载为压缩的csv文件。它是现场的并且有效。

public ActionResult L2CSV()
{
    var posts = _dataItemService.SelectStuff();
    string csv = CSV.IEnumerableToCSV(posts);
    // These first two lines simply get our required data as a long csv string
    var fileData = Zip.CreateZip("LogPosts.csv", System.Text.Encoding.UTF8.GetBytes(csv));
    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = "LogPosts.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");
}

答案 1 :(得分:0)

您可以使用:

zip.Save(ms);

// Set read point to beginning of stream
ms.Position = 0;

ZipFile newZip = ZipFile.Read(ms);

答案 2 :(得分:0)

请参阅the documentation了解使用从流中获取的内容创建zip。

  using (ZipFile zip = new ZipFile())
  {
    ZipEntry e= zip.AddEntry("Content-From-Stream.bin", "basedirectory", StreamToRead);
    e.Comment = "The content for entry in the zip file was obtained from a stream";
    zip.AddFile("Readme.txt");
    zip.Save(zipFileToCreate);
  }

保存后,您可以正常打开它。

相关问题