1

我正在使用 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();
        }
4

1 回答 1

0

ZipArchive 在处理流时会向流中添加一些附加信息(例如校验和),因此您不应在处理 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");
}
于 2018-01-03T16:16:07.250 回答