在我的c#代码中,我试图创建一个压缩文件夹,供用户在浏览器中下载。所以这里的想法是,用户点击下载按钮,然后得到一个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 ={“试图在流开始之前移动该位置”}
异常发生在
使用(ZipArchive zip =新ZipArchive(ms))
有什么想法吗?
发布于 2015-11-13 07:03:26
您在创建ZipArchive时没有指定模式,这意味着它首先尝试从它读取,但是没有什么可读取的。您可以通过在构造函数调用中指定ZipArchiveMode.Create来解决这个问题。
另一个问题是,在关闭MemoryStream之前,要将ZipArchive写入输出.这意味着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);
}https://stackoverflow.com/questions/33687425
复制相似问题