Introduction to ZipArchive in C# Programming — Webner Blog
Introduction
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("/NewZip.zip");
using(ZipArchive archive = ZipFile.Open(createZipPath , ZipArchiveMode.Create))
{
List<string> files = new List<string>();
files.Add("pic1.jpg");
files.Add("pic2.jpg");
files.Add("pic3.jpg");
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 NewZip.zip 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.
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.
Originally published at https://blog.webnersolutions.com on August 10, 2020.