Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Web API return Zip File from memory stream

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

like image 538
Briz Avatar asked May 14 '20 07:05

Briz


1 Answers

I figured out the issue.

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

like image 121
Briz Avatar answered Nov 05 '22 20:11

Briz