Title: Compress and decompress directories in C#
The ZipFile class provides remarkably simple methods to compress and decompress directories in the zip format. This class is defined in the .NET Framework version 4.5, so this example is in Visual Studio 2017 instead of an older version.
To use the class, you need to add a reference to the System.IO.Compression.FileSystem library. This example also includes using directives for System.IO.Compression (where the class is) and System.IO (because the code uses the Path class).
When the program starts, the following code executes.
// Add a reference to System.IO.Compression.FileSystem.
using System.IO.Compression;
using System.IO;
...
// Start with the source folder.
private void Form1_Load(object sender, EventArgs e)
{
txtFolder.Text = Application.StartupPath;
txtZipFile.Text = Path.GetFullPath(
Path.Combine(Application.StartupPath,
"..\\howto_zip_folder.zip"));
}
The first line makes the folder text box hold the path to the executable program's folder. The second line makes the zip file text box hold the name howto_zip_folder.zip in the directory one level above the executable program's directory. You can change those values at runtime if you like.
When you click the Zip button, the following code executes.
// Zip the directory.
private void btnZip_Click(object sender, EventArgs e)
{
try
{
ZipFile.CreateFromDirectory(txtFolder.Text,
txtZipFile.Text);
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The key is the call to the ZipFile class's static CreateFromDirectory method. This method compresses the directory with name given by the first parameter and creates the zip file with name given by the second parameter. The rest of this code is error handling. For example, the code throws an exception if the zip file already exists.
When you click the Unzip button, the following code executes.
// Unzip the zip file.
private void btnUnzip_Click(object sender, EventArgs e)
{
try
{
ZipFile.ExtractToDirectory(txtZipFile.Text,
txtFolder.Text);
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The key here is the call to the ZipFile class's ExtractToDirectory method. Its parameters give the name of the zip file to decompress and the name of the directory where you want the results to land. As when compressing, most of this code is error handling.
Note that when you decompress, the directory where you want the results placed can exist, but the method will throw an exception if it tries to create a file that already exists.
Download the example to experiment with it and to see additional details.
|