C#, Microsoft Windows

How to create zip file using C#

To create zip files we are going to use the DotNetZip library.

Create zip file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// <summary>
/// add files into zip and save
/// </summary>
/// <param name="zipfile"></param>
/// <param name="files"></param>
public void createArchive(String zipfile, List<String> files)
{
	ZipFile zip = new ZipFile(); //or ZipFile zip = new ZipFile(Encoding.UTF8);
	foreach (String file in files)
	{
	    zip.AddFile(file);
	}
	zip.Save(zipfile);
}

or

1
2
3
4
5
6
7
8
9
10
11
/// <summary>
/// add files into zip and save
/// </summary>
/// <param name="zipfile"></param>
/// <param name="files"></param>
public void createArchive(String zipfile, List<String> files)
{
	ZipFile zip = new ZipFile(); //or ZipFile zip = new ZipFile(Encoding.UTF8);
	zip.AddFiles(files);
	zip.Save(zipfile);
}

Unzip archive file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// <summary>
/// extract files from zip to specified directory
/// </summary>
/// <param name="zipfile"></param>
/// <param name="directory2extract"></param>
public void extractArchive(String zipfile, String directory2extract)
{
	ZipFile zip = ZipFile.Read(zipfile);
 
	foreach (ZipEntry e in zip)
	{
	    e.Extract(directory2extract, ExtractExistingFileAction.OverwriteSilently);
	}
}