ZipArchive 生成​​的 zip 文件未解压

ZipArchive generated zip file not extracted

我使用 System.IO.Compression.ZipArchive 在 .Net Core 3.1 WebAPI 中生成 zip 文件。生成的zip文件可以用7-zip打开或解压,但默认Windows命令不起作用

    [HttpPost]
    public async Task<IActionResult> Download()
    {
        byte[] zipFile;
        using (var ms = new MemoryStream())
        using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
        {
            var fileFullPath = "C:\temp\a.pdf";

            zipArchive.CreateEntryFromFile(fileFullPath, $"a.pdf", CompressionLevel.Fastest);

            ms.Position = 0;
            zipFile = ms.ToArray();
        }

        System.IO.File.WriteAllBytes("C:\temp\test.zip", zipFile);

        return File(zipFile, MediaTypeNames.Application.Zip, $"test.zip");
    }

我可以从 swagger 页面下载 test.zip 文件或查看文件大小合适的 C:\temp\test.zip。 但是我无法在文件资源管理器中右键单击该文件来提取它。

有什么想法吗?

更新:

如果我创建新文件夹并复制该文件夹下的所有文件,然后调用ZipFile.CreateFromDirectory,文件生成并可以通过Windows 资源管理器或WinZip 提取。还在疑惑为什么 ZipArchive 做不出来。我正在尝试在内存中创建 zip 流而不是在磁盘上创建 zip 文件。

刚刚发现问题是重复的,但我不想删除这个问题。更正后的代码:

        [HttpPost]
    public async Task<IActionResult> Download()
    {
        byte[] zipFile;
        using (var ms = new MemoryStream())
        {
            using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
            {
                var fileFullPath = "C:\temp\a.pdf";

                zipArchive.CreateEntryFromFile(fileFullPath, "a.pdf", CompressionLevel.Fastest);

            }

            ms.Position = 0;
            zipFile = ms.ToArray();
        }

        return File(zipFile, MediaTypeNames.Application.Zip, $"test.zip");
    }

在这里使用语句大括号很重要。

在读回写入 MemoryStream 的字节之前,您必须清除所有缓冲数据并通过关闭它来完成 zip 存档,这就是将中央目录记录写入 zip 文件的原因。