首页 > 解决方案 > 从不同的文件路径在内存中创建 Zip 文件并在 C# 中下载

问题描述

我试图使用ZipArchive类从不同的位置创建和下载一个 zip 文件。

这些文件位于不同的文件路径中。我想在 c# in-memory 对象中创建一个 zip 文件,然后下载它而不将 zip文件保存在 c#/MVC 中。

我试过这样:

public void DownloadZipFromMultipleFile()
{
   using (var memoryStream = new MemoryStream())
   {
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
      {
         archive.CreateEntryFromFile(Server.MapPath("~/Content/appStyle.css"), "myStyle.css");
         archive.CreateEntryFromFile(Server.MapPath("~/NewPath/myScript.js"), "script.js");
      }
   }

   //archive.Save(Response.OutputStream);
}

我已成功将文件添加到archive但无法将文件下载为 zip 文件。

标签: c#asp.net-mvcmodel-view-controller

解决方案


正如PapitoSh在评论部分所建议的那样,我在现有代码中添加了几行代码,现在它工作正常。

public void DownloadZipFromMultipleFile()
{
   using (var memoryStream = new MemoryStream())
   {
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
      {
         archive.CreateEntryFromFile(Server.MapPath("~/Content/appStyle.css"), "myStyle.css");
         archive.CreateEntryFromFile(Server.MapPath("~/NewPath/myScript.js"), "script.js");
      }

      byte[] bytesInStream = memoryStream.ToArray(); // simpler way of converting to array 
      memoryStream.Close(); 
      Response.Clear(); 
      Response.ContentType = "application/force-download"; 
      Response.AddHeader("content-disposition", "attachment; filename=name_you_file.zip"); 
      Response.BinaryWrite(bytesInStream); Response.End();
   }

   //archive.Save(Response.OutputStream);
}

推荐阅读