ZipArchive提供意外的数据损坏错误结束 [英] ZipArchive gives Unexpected end of data corrupted error

查看:137
本文介绍了ZipArchive提供意外的数据损坏错误结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a zip stream on the fly with some byte array data and make it download via my MVC action.

但是在Windows中打开时,下载的文件始终会出现以下损坏的错误.

But the downloaded file always gives the following corrupted error when opened in windows.

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

And this error when I try to xtract from 7z

但是请注意,从7z提取的文件未损坏.

But note that the files extracted from the 7z is not corrupted.

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

I'm using ZipArchive and the below is my code.

    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");
    }

我在这里做错了什么.

在整整一天的时间里,我将竭尽全力为您提供帮助.

Any help would be highly appreciated as I'm struggling with this for a whole day.

预先感谢

推荐答案

zipStream.ToArray()移动到zipArchive之外.

您的问题的原因是流已缓冲.有几种解决方法:

The reason for your problem is that the stream is buffered. There's a few ways to deal wtih it:

  • 您可以将流的AutoFlush属性设置为true.
  • 您可以在流中手动调用.Flush().
  • You can set the stream's AutoFlush property to true.
  • You can manually call .Flush() on the stream.

或者,由于它是MemoryStream并且您正在使用.ToArray(),因此您可以简单地首先允许流被关闭/处理(我们通过将其移到using之外来完成).

Or, since it's MemoryStream and you're using .ToArray(), you can simply allow the stream to be Closed/Disposed first (which we've done by moving it outside the using).

这篇关于ZipArchive提供意外的数据损坏错误结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆