在我的 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/