我正在使用ZipArchive并且它主要工作,我看到的一个问题是当文件下载时我无法使用Windows默认存档例程打开它。如果我单击zip文件并提取所有内容,我会收到一条错误消息,指出没有要提取的条目。任何人都知道为什么会这样吗?为了它的价值,我可以用7zip打开同一个文件并提取文件就好了。
public virtual ActionResult GetZip()
{
var summary = GetBytes();
var response = new MemoryStream();
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
var entry = archive.CreateEntry("myfiletozip" + fileExt);
using (var writer = new BinaryWriter(entry.Open()))
{
writer.Write(summary, 0, summary.Length);
}
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(response);
}
}
response.Seek(0, SeekOrigin.Begin);
return this.File(response, MediaTypeNames.Application.Zip, "myzipfilename.zip");
}
更新:
找到这个SO Answer并修改了我的来源,它正在工作......我仍然不知道为什么。
byte[] response;
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
var entry = archive.CreateEntry("myfiletozip" + fileExt, CompressionLevel.Optimal);
using (var entryStream = entry.Open())
using (var fileToCompressStream = new MemoryStream(summary))
{
fileToCompressStream.CopyTo(entryStream);
}
}
response = stream.ToArray();
}
答案 0 :(得分:0)
ZipArchive在处理流时会向流中添加一些额外的信息(例如.checksum),因此在放置ZipArchive对象之前,不应该寻找流或使用它。
public virtual ActionResult GetZip()
{
var summary = GetBytes();
var response = new MemoryStream();
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
var entry = archive.CreateEntry("myfiletozip" + fileExt);
using (var writer = new BinaryWriter(entry.Open()))
{
writer.Write(summary, 0, summary.Length);
}
}
//Use stream after archive is disposed
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(response);
}
response.Seek(0, SeekOrigin.Begin);
return this.File(response, MediaTypeNames.Application.Zip, "myzipfilename.zip");
}