首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ziparchive中的中心目录损坏错误

ziparchive中的中心目录损坏错误
EN

Stack Overflow用户
提问于 2015-11-13 07:01:49
回答 1查看 24.2K关注 0票数 19

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

为了测试目的,我使用一个文件并压缩它,但当它工作时,我将有多个文件。

这是我的密码

代码语言:javascript
复制
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 ={“试图在流开始之前移动该位置”}

异常发生在

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

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-13 07:03:26

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

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

代码语言:javascript
复制
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);
 }
票数 34
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33687425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档