Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip multiple files using only .net api in c#

I like to zip multiple files which are being created dynamically in my web application. Those files should be zipped. For this, i dont want to use any third-party tools. just like to use .net api in c#

like image 562
Partha Avatar asked Aug 07 '09 09:08

Partha


People also ask

How do I zip multiple files at once?

Right-click on the file or folder. Select “Compressed (zipped) folder”. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.

How do I send multiple files to a compressed folder?

Zipping Multiple FilesHold down [Ctrl] on your keyboard > Click on each file you wish to combine into a zipped file. Right-click and select "Send To" > Choose "Compressed (Zipped) Folder."


2 Answers

With the release of the .NET Framework 4.5 this is actually a lot easier now with the updates to System.IO.Compression which adds the ZipFile class. There is a good walk-through on codeguru; however, the basics are in line with the following example:

using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.IO.Compression.FileSystem;  namespace ZipFileCreator {     public static class ZipFileCreator     {         /// <summary>         /// Create a ZIP file of the files provided.         /// </summary>         /// <param name="fileName">The full path and name to store the ZIP file at.</param>         /// <param name="files">The list of files to be added.</param>         public static void CreateZipFile(string fileName, IEnumerable<string> files)         {             // Create and open a new ZIP file             var zip = ZipFile.Open(fileName, ZipArchiveMode.Create);             foreach (var file in files)             {                 // Add the entry for each file                 zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);             }             // Dispose of the object when we are done             zip.Dispose();         }     } } 

like image 79
rjzii Avatar answered Oct 13 '22 23:10

rjzii


Use System.IO.Packaging in .NET 3.0+.

See this introduction to System.IO.Packaging


If you're able to take a .NET 4.5 dependency, there's a System.IO.Compression.ZipArchive in that universe; see walkthrough article here (via InfoQ news summary article here)

like image 30
Ruben Bartelink Avatar answered Oct 13 '22 22:10

Ruben Bartelink