download multiple files as zip in .net

前端 未结 4 679
日久生厌
日久生厌 2020-12-13 11:45

i have a file list with check box for each files , if the user checks many files and click download i have to zip all those files and download it... like in mails attachment

相关标签:
4条回答
  • 2020-12-13 11:47

    The 3 libraries I know of are SharpZipLib (versatile formats), DotNetZip (everything ZIP), and ZipStorer (small and compact). No links, but they are all on codeplex and found via google. The licenses and exact features vary.

    Happy coding.

    0 讨论(0)
  • 2020-12-13 11:56

    Create a ZIP file on the fly using http://www.icsharpcode.net/opensource/sharpziplib/.

    0 讨论(0)
  • 2020-12-13 12:10

    This is how to do it the DotNetZip way :D I vouch for DotNetZip because I have used it and it is by far the easiest compression library for C# I've come across :)

    Check http://dotnetzip.codeplex.com/

    http://dotnetzip.codeplex.com/wikipage?title=CS-Examples&referringTitle=Examples

    Create a downloadable zip within ASP.NET. This example creates a zip dynamically within an ASP.NET postback method, then downloads that zipfile to the requesting browser through Response.OutputStream. No zip archive is ever created on disk.

    public void btnGo_Click (Object sender, EventArgs e)
    {
      Response.Clear();
      Response.BufferOutput= false;  // for large files
      String ReadmeText= "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G");
      string filename = System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text) + ".zip";
      Response.ContentType = "application/zip";
      Response.AddHeader("content-disposition", "filename=" + filename);
    
      using (ZipFile zip = new ZipFile()) 
      {
        zip.AddFile(ListOfFiles.SelectedItem.Text, "files");
        zip.AddEntry("Readme.txt", "", ReadmeText);
        zip.Save(Response.OutputStream);
      }
      Response.Close();
    }
    
    0 讨论(0)
  • 2020-12-13 12:13

    You need to pack files and write a result to a response. You can use SharpZipLib compression library.

    Code example:

    Response.AddHeader("Content-Disposition", "attachment; filename=" + compressedFileName + ".zip");
    Response.ContentType = "application/zip";
    
    using (var zipStream = new ZipOutputStream(Response.OutputStream))
    {
        foreach (string filePath in filePaths)
        {
            byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
    
            var fileEntry = new ZipEntry(Path.GetFileName(filePath))
            {
                Size = fileBytes.Length
            };
    
            zipStream.PutNextEntry(fileEntry);
            zipStream.Write(fileBytes, 0, fileBytes.Length);
        }
    
        zipStream.Flush();
        zipStream.Close();
    }
    
    0 讨论(0)
提交回复
热议问题