.NET Core Web API return Zip File from memory stream

Viewed 5667

I am trying to create a Zip file in memory adding in some other files as entries to the archive and return it from my Web API Controller using the following:

try {
    // Create Zip Archive in Memory
    MemoryStream memoryStream = new MemoryStream();
    ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create);
    foreach(Worksheet w in worksheets) {
        string fullPath = Path.Combine(baseFolder, w.FilePathAndName);
        if(System.IO.File.Exists(fullPath)) {
            ZipArchiveEntry f = zipArchive.CreateEntry(w.FileName, CompressionLevel.Fastest);
            using(Stream entryStream = f.Open()) {
                FileStream fileStream = System.IO.File.OpenRead(fullPath);
                await fileStream.CopyToAsync(entryStream);
            }
        }
    }
    memoryStream.Seek(0, SeekOrigin.Begin);
    return File(memoryStream, "application/zip", $"Files.zip");
} catch(Exception e) {
    return StatusCode(500, "Error: Could not generate zip file");
}

This does create and return a zip file however, it is invalid. 7-Zip gives me this error

Running unzip -t Files.zip to test the archive results in the following:

  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
note:  Files.zip may be a plain executable, not an archive
unzip:  cannot find zipfile directory in one of Files.zip or
        Files.zip.zip, and cannot find Files.zip.ZIP, period.

.NET Core version 3.1.201

2 Answers

I figured out the issue.

I needed to call zipArchive.Dispose() before memoryStream.Seek(0, SeekOrigin.Begin);

Another option would be to have zipArchive in using clause, like this:

    using (var memoryStream = new MemoryStream())
            {
                using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    for (var i = 0; i < images.Count; i++)
                    {
                        var fileInArchive = zipArchive.CreateEntry(fileNames[i], CompressionLevel.Optimal);
                        using (var entryStream = fileInArchive.Open())
                        using (var fileToCompressStream = new MemoryStream(images[i]))
                        {
                            fileToCompressStream.CopyTo(entryStream);
                        }
                    }
                }

                using (var fileStream = new FileStream(zipPath, FileMode.Create))
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    memoryStream.CopyTo(fileStream);
                }
            }

The garbage collector will dispose it automatically once it exits the using clause and there is no need to call dispose explicitly.

Related