Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zip files in server

Tags:

c#

asp.net

zip

How can I zip (In the server) multiple files to one archive?

like image 478
user452738 Avatar asked Jul 02 '26 04:07

user452738


1 Answers

Following code uses our Rebex ZIP and shows how to add files into the ZIP archive without using any temp file. The ZIP is then sent to the web browser.

// prepare MemoryStream to create ZIP archive within
using (MemoryStream ms = new MemoryStream())
{
    // create new ZIP archive within prepared MemoryStream
    using (ZipArchive zip = new ZipArchive(ms))
    {            
         // add some files to ZIP archive
         zip.Add(@"c:\temp\testfile.txt");
         zip.Add(@"c:\temp\innerfile.txt", @"\subfolder");

         // clear response stream and set the response header and content type
         Response.Clear();
         Response.ContentType = "application/zip";
         Response.AddHeader("content-disposition", "filename=sample.zip");

         // write content of the MemoryStream (created ZIP archive) 
         // to the response stream
         ms.WriteTo(Response.OutputStream);
    }
}

// close the current HTTP response and stop executing this page
HttpContext.Current.ApplicationInstance.CompleteRequest();

For more info see ZIP tutorial.

Alternative solution:

SharpZipLib and DotNetZip a widely used free alternatives.

like image 129
Martin Vobr Avatar answered Jul 03 '26 17:07

Martin Vobr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!