c# - ziarchive 中的中央目录损坏错误

标签 c# ziparchive

在我的 C# 代码中,我试图创建一个 zip 文件夹供用户在浏览器中下载。所以这里的想法是,用户点击下载按钮,他会得到一个 zip 文件夹。

出于测试目的,我使用单个文件并将其压缩,但当它工作时,我将有多个文件。

这是我的代码

var outPutDirectory = AppDomain.CurrentDomain.BaseDirectory;
string logoimage = Path.Combine(outPutDirectory, "images\\error.png"); // I get the file to be zipped

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = false;
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=pauls_chapel_audio.zip");


using (MemoryStream ms = new MemoryStream())
     {
          // create new ZIP archive within prepared MemoryStream
          using (ZipArchive zip = new ZipArchive(ms))
             {
                    zip.CreateEntry(logoimage);
                    // add some files to ZIP archive

                    ms.WriteTo(HttpContext.Current.Response.OutputStream);
             }
     }

当我尝试这个东西时它给我这个错误

Central Directory corrupt.

[System.IO.IOException] = {"An attempt was made to move the position before the beginning of the stream."}

异常发生在

using (ZipArchive zip = new ZipArchive(ms))

有什么想法吗?

最佳答案

您在创建 ZipArchive 时没有指定模式,这意味着它首先尝试从中读取数据,但没有任何数据可读取。您可以通过在构造函数调用中指定 ZipArchiveMode.Create 来解决这个问题。

另一个问题是您在关闭ZipArchive之前将MemoryStream写入输出...这意味着ZipArchive 代码没有机会做任何内务处理。您需要将写入部分移到嵌套的 using 语句之后 - 但请注意,您需要更改创建 ZipArchive 的方式以保持流打开状态:

using (MemoryStream ms = new MemoryStream())
{
    // Create new ZIP archive within prepared MemoryStream
    using (ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        zip.CreateEntry(logoimage);
        // ...
    }        
    ms.WriteTo(HttpContext.Current.Response.OutputStream);
 }

关于c# - ziarchive 中的中央目录损坏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33687425/

相关文章:

c# - 在 ASP.NET 中链接两个表单

c# - Foreach Razor 内部的 Foreach

c# - ZipArchive 创建无效的 ZIP 文件

c# - IIS7.5 Server.ClearError()不起作用

c# - WCF 作为应用程序工作,而不是作为服务

php - 在本地主机上启用 ZipArchive

objective-c - objective-c : How to know the progress of unzipping in using ZipArchive

php - PHP 中的 zipArchive 打开错误

Php 创建 zip 文件(来自帖子附件 wordpress)

c# - 从 C# 到 Java