Compress and decompress directories in C#

[compress and decompress directories]

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.

// 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.

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 of 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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in classes, directories, files and tagged , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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