How to create ZIP file using C#? How to compress and decompress files using C#?

Previously, we had to use some thrid party softwares or plugins to create ZIP archive files. Now in .NET Framework 4.5, new namespace is added. It is very simple and one line code. :)

  • System.IO.Compression
  • System.IO.Compression.FileSystem

 Some when we are having so many attachments to be downloaded all together. It is a better option to provide user that they can download all files in ZIP file. GMail also provides the same feature when we have more attachments.

To start working on this using c#, we have add reference of above mentioned two assemblies and import System.IO.Compression namespace.

This namespace has below classes:

  • ZipFile - ZipFile class has static methods for creating, opening and extracting zip files.
  • ZipArchive - ZipArchive class allows to handle bundle of files that are compressed.
  • ZipArchiveEntry - A ZipArchive typically consists of one or more ZipArchiveEntry instances. ZipArchiveEntry represents a single entry from ZipArchive.
  • DeflateStream
  • GZipStream
Examples:
//Creating ZIP file and Extracting ZIP file
using System.IO.Compression;

public partial class Zip : System.Web.UI.Page
{
    protected void btnCreateSampleZip_Click(object sender, EventArgs e)
    {
        //Creating a unique file name.
        string zipName = String.Join("", DateTime.Now.ToString().Split('/', ' ', ':')) + ".zip";
        string sourcePath = @"D:\MyProjects\MT\Data\User1023";
        string zipPath = @"D:\MyProjects\MT\Data\" + zipName;
        string extractPath = @"D:\MyProjects\MT\Data\Test";
        //Creating ZIP file.
        ZipFile.CreateFromDirectory(sourcePath, zipPath);
        //Extracting ZIP file.
        ZipFile.ExtractToDirectory(zipPath, extractPath);
    }
}
//Creating ZIP of files from different folders

//Add your files here
string[] files = txtfile.Text.Split(',');
//Creating a unique file name.
string zipName = String.Join("", DateTime.Now.ToString().Split('/', ' ', ':')) + ".zip";
string sourcePath = @"D:\MyProjects\MT\Data\User1023";
string zipPath = @"D:\MyProjects\MT\Data\" + zipName;

ZipArchive zip = ZipFile.Open(zipPath, ZipArchiveMode.Create);
foreach (string file in files)
{
    //Adding file to ZIP file.
    zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
}
zip.Dispose();

 For more details refer below links:

https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchivemode.aspx

https://msdn.microsoft.com/en-us/library/ms404280(v=vs.110).aspx

Add comment

Loading