.NET Core Created Zip Archive已损坏

时间:2017-07-03 18:38:31

标签: c# asp.net zip .net-core

我正在创建一个web api路由,它接受一个字节数组列表并从中创建一个zip文件。但是,返回的文件已损坏,我无法使用Windows默认的zip提取器提取它的内容(我可以使用7-zip打开并正确提取它)。可能的原因是什么?

 using (var stream = new MemoryStream())
 using (var zipArchive = new ZipArchive(stream, ZipArchiveMode.Create))
 {
   var i = 1;
   foreach(var file in files)
   {
     var zipEntry = zipArchive.CreateEntry($"{i}.txt");

     using (var zipStream = zipEntry.Open())
     {
        zipStream.Write(file, 0, file.Length);
     }
     i++;
  }

stream.Seek(0, SeekOrigin.Begin);
return new FileContentResult(stream.ToArray(), "application/octet-stream") { FileDownloadName = "Splitted.zip" };

}

当我创建一个zip存档时,有人能指导我做错了什么吗?

编辑: 我甚至尝试使用包含“hello”字符串的单个文本文件创建一个zip,但仍然无法打开:

[HttpGet]
[Route("asd")]
public IActionResult Getasd()
{
    using (var stream = new MemoryStream())
    using (var zipArchive = new ZipArchive(stream, ZipArchiveMode.Create))
    {
        var text = "hello";
        var bytes = Encoding.UTF8.GetBytes(text);

        var zipEntry = zipArchive.CreateEntry($"asd.txt", CompressionLevel.NoCompression);

        using (var memStream = new MemoryStream(bytes))
        using (var zipStream = zipEntry.Open())
        {
            memStream.CopyTo(zipStream);
        }

        return new FileContentResult(stream.ToArray(), "application/octet-stream") { FileDownloadName = "Splitted.zip" };
    }
}

0 个答案:

没有答案