【问题标题】:How to open up a zip file from MemoryStream如何从 MemoryStream 打开一个 zip 文件
【发布时间】:2012-12-19 01:03:53
【问题描述】:

我正在使用 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 文件,以便用户可以访问所有文件

【问题讨论】:

标签: c# dotnetzip


【解决方案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");
}

【讨论】:

    【解决方案2】:

    你可以使用:

    zip.Save(ms);
    
    // Set read point to beginning of stream
    ms.Position = 0;
    
    ZipFile newZip = ZipFile.Read(ms);
    

    【讨论】:

    • 谢谢,但我无法打开 zip 文件以便用户查看所有已压缩的文件
    【解决方案3】:

    请参阅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);
      }
    

    保存后就可以正常打开了。

    【讨论】:

    • 嗨 Bobson,当我按照你提到的方式进行操作时,它无法弄清楚 StreamToRead 是什么。
    • @WebDev - 在你的情况下,你应该把ms放在那里,因为那是你的MemoryStream
    • 不确定这是否符合我的预期。我可能没有解释清楚。
    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多