.NET Core Web API 从内存流返回 Zip 文件

Bri*_*riz 4 .net memorystream zipfile .net-core asp.net-core-webapi

我正在尝试在内存中创建一个 Zip 文件,将其他一些文件添加为存档条目,并使用以下命令从我的 Web API 控制器返回它:

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");
}
Run Code Online (Sandbox Code Playgroud)

这会创建并返回一个 zip 文件,但是它是无效的。7-Zip 给了我这个错误

运行unzip -t Files.zip以测试存档结果如下:

  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.
Run Code Online (Sandbox Code Playgroud)

.NET 核心版本 3.1.201

Bri*_*riz 5

我想通了这个问题。

zipArchive.Dispose()之前需要打电话memoryStream.Seek(0, SeekOrigin.Begin);