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
I figured out the issue.
I needed to call zipArchive.Dispose()
before memoryStream.Seek(0, SeekOrigin.Begin);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With