中央目录在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); } } 

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

中央目录损坏。

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

exception发生在

使用(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); }