【问题标题】:Creating a zip archive from memory stream in .Net Core从 .Net Core 中的内存流创建 zip 存档
【发布时间】:2022-06-24 22:20:18
【问题描述】:

我正在尝试从内存流创建一个 zip 存档,当我从 Web 端的 API 下载它时,它告诉我存档已损坏,当我尝试打开它时(仅此而已,下载本身成功)。

这是我用于生成 zip-archive 的代码:

    public byte[] ZipFiles(IEnumerable<FileContentResult> filesToZip)
    {
        var outputMemoryStream = new MemoryStream();
        var zipStream = new ZipOutputStream(outputMemoryStream);

        zipStream.SetLevel(3);

        foreach (var fileToZip in filesToZip)
        {
            var inputMemoryStream = new MemoryStream(fileToZip.FileContents);
            var zipEntry = new ZipEntry(fileToZip.FileDownloadName);
            zipEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(zipEntry);
            StreamUtils.Copy(inputMemoryStream, zipStream, new byte[4096]);
            zipStream.CloseEntry();
        }

        zipStream.IsStreamOwner = false;
        zipStream.Close();

        outputMemoryStream.Position = 0;

        return outputMemoryStream.ToArray();
    }

它将 zip 文件作为字节数组返回,然后将其放入另一个文件内容结果中,然后再从 API 返回(我尝试将 contenttype 设置为 application/octet-streamapplication/zip)。我已经在 stackoverflow 上看到并尝试了大量不同的解决方案,但是在尝试打开下载的文件时,它们似乎都失败了。我正在使用 SharpZipLib。有大佬指点一下吗?

编辑/新信息: 经过进一步的测试/调试,似乎 zip 文件本身还可以。如果我将它保存到服务器磁盘,我就可以打开/解压缩文件。但是,将其放入 filecontentresult 并从控制器返回并在客户端上下载它的操作似乎破坏了它。文件名没问题,扩展名为 .zip,如前所述,我已尝试将 application/octet-streamapplication/zip 作为内容类型(我认为第二个使用正确)。我们已经从 API 中返回并下载了其他文件就好了,只是 zip 文件在此处无法正常工作。

【问题讨论】:

    标签: .net-core memorystream sharpziplib


    【解决方案1】:

    如果我没记错的话,你必须使用 Seek(0, SeekOrigin.Begin) 将内存流搜索到流的开头并释放 zip。

    【讨论】:

      猜你喜欢
      • 2020-08-30
      • 2012-04-18
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 2016-09-23
      • 1970-01-01
      相关资源
      最近更新 更多