gpt4 book ai didi

c# - ZipArchive 给出数据损坏错误的意外结束

转载 作者:可可西里 更新时间:2023-11-01 08:05:25 28 4
gpt4 key购买 nike

我正在尝试使用一些字节数组数据动态创建一个 zip 流,并通过我的 MVC 操作下载它。

但是下载的文件在windows中打开时总是出现以下损坏的错误。

enter image description here

当我尝试从 7z xtract 时出现此错误

enter image description here

但请注意,从 7z 中提取的文件没有损坏。

我正在使用 ZipArchive,下面是我的代码。

    private byte[] GetZippedPods(IEnumerable<POD> pods, long consignmentID)
{
using (var zipStream = new MemoryStream())
{
//Create an archive and store the stream in memory.
using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
int index = 1;
foreach (var pod in pods)
{
var zipEntry = zipArchive.CreateEntry($"POD{consignmentID}{index++}.png", CompressionLevel.NoCompression);
using (var originalFileStream = new MemoryStream(pod.ByteData))
{
using (var zipEntryStream = zipEntry.Open())
{
originalFileStream.CopyTo(zipEntryStream);
}
}
}
return zipStream.ToArray();
}
}
}

public ActionResult DownloadPOD(long consignmentID)
{
var pods = _consignmentService.GetPODs(consignmentID);
var fileBytes = GetZippedPods(pods, consignmentID);
return File(fileBytes, MediaTypeNames.Application.Octet, $"PODS{consignmentID}.zip");
}

我在这里做错了什么。

任何帮助将不胜感激,因为我为此苦苦挣扎了一整天。

提前致谢

最佳答案

使用 zipArchivezipStream.ToArray() 移出。

你的问题的原因是流被缓冲了。有几种方法可以处理它:

  • 您可以将流的 AutoFlush 属性设置为 true
  • 您可以在流上手动调用 .Flush()

或者,因为它是 MemoryStream 并且您正在使用 .ToArray(),您可以简单地允许首先关闭/处置流(我们已经完成了通过将它移到 using 之外)。

关于c# - ZipArchive 给出数据损坏错误的意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707862/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com