ZipArchive in C#

| By Webner


ZipArchive is a built-in package in the System.IO.Compression assembly to compress/decompress files in a zip format in C# code. It allows us to work with a collection of compressed files. For this we can do the following things:

  • Get a single entry of file from the package using the GetEntry() method.
  • Get an entire collection of entries (files) from the package using Entries property.
  • Create a new entry in the package by invoking the CreateEntry() overloads.

When we create a new entry, the file is compressed and added to the zip package. We include the relative path of the new entry within the zip package. For example, creating a new entry with a relative path of NewlyAddedFolder\TFile.txt creates a compressed text file in a directory named NewlyAddedFolder.

To use ZipArchive, first, we need to add a reference to the System.IO.Compression assembly.


string createZipPath = System.Web.Hosting.HostingEnvironment.MapPath("/");
using(ZipArchive archive = ZipFile.Open(createZipPath , ZipArchiveMode.Create))
List<string> files = new List<string>();
foreach(string file in files)
string filePath = “path where files are stored”;
archive.CreateEntryFromFile(filePath, file);

The above code will Zip the files pic1.jpg , pic2.jpg , pic3.jpg into file.

Similarly we can extract these file from Zip file using :
archive.ExtractToDirectory(zipPath, ExtractPath);

Similarly, there are other functions in ZipArchive to handle Zip files.

To Use
Create zip archive from a directory ZipFile.CreateFromDirectory
Extract contents of a zip archive ZipFile.ExtractToDirectory
Add a new file to the already existing zip archive ZipArchive.CreateEntry
Retrieve a file from a zip archive ZipArchive.GetEntry
Retrieve all files from a zip archive ZipArchive.Entries
Open stream to a single file ZipArchiveEntry.Open
Delete a file from a zip archive ZipArchiveEntry.Delete


Leave a Reply

Your email address will not be published. Required fields are marked *