中央目录在ziparchive中的损坏错误

moh*_*317 8 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);
             }
     }
Run Code Online (Sandbox Code Playgroud)

当我尝试这件事时,它给了我这个错误

中央目录损坏.

[System.IO.IOException] = {"试图在流的开头之前移动位置."}

异常发生在

使用(ZipArchive zip = new ZipArchive(ms))

有什么想法吗?

Jon*_*eet 21

你创建的是ZipArchive没有指定模式,这意味着它首先尝试从中读取,但是没有什么可读的.您可以通过ZipArchiveMode.Create在构造函数调用中指定来解决此问题.

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

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);
 }
Run Code Online (Sandbox Code Playgroud)

  • @ChaudhryMohsinAli:我不是ASP.NET开发人员,但我相信这取决于你使用的是什么版本等."HttpServerUtility.MapPath"是一种方式,但现在可能有更好的方法. (3认同)
  • @ChaudhryMohsinAli:如果这是从ASP.NET运行的,那么文件可能不在您认为的位置......您可能希望首先解析相对于Web上下文的文件名. (2认同)