-1

I use System.IO.Compression.ZipArchive to generate zip file in .Net Core 3.1 WebAPI. The generated zip file can be opened or extracted by 7-zip, but it does not work by default Windows command.

    [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");
    }

I can download test.zip file from swagger page or see C:\temp\test.zip with fair file size. But I can't right click the file in file explorer to extract it.

enter image description here

Any ideas?

Update:

If I create new folder and copy all files under the folder, then call ZipFile.CreateFromDirectory, file is generated and able to be extracted by Windows explorer or WinZip. Still wonder why ZipArchive can't make it. I'm trying to create zip stream in memory instead of zip file on disk.

Just found out the question is duplicate, but I would like to keep this question from deleting. Corrected code:

        [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");
    }
Jason Li
  • 1,194
  • 2
  • 11
  • 17

1 Answers1

3

Using statement braces matter here.

You have to flush out any buffered data and finish the zip archive, by closing it, which is what writes the central directory record into the zip file, before you read back the bytes written to the MemoryStream.

Tim Lovell-Smith
  • 15,310
  • 14
  • 76
  • 93