.NET Framework, Software Development

Zip It Good: A Punny Guide to Compressing Files in C#!

Data compression is a process of reducing the size of data while maintaining its integrity and usefulness. It is useful in reducing the amount of storage and bandwidth required for storing and transferring data. There are various compression algorithms available for compressing data, and one of the most commonly used is the Deflate algorithm, which is used in popular compression formats such as ZIP, GZIP, and PNG.

C# provides a built-in namespace System.IO.Compression for working with compressed data. In this tutorial, we will learn how to use this namespace to compress and decompress files and folders.

Step 1: Adding the Namespace

To begin with, we need to add the System.IO.Compression namespace to our code file. We can add this namespace using the following code:

using System.IO.Compression;

Step 2: Compressing a File

We can compress a file using the GZipStream class provided by the System.IO.Compression namespace. The GZipStream class provides methods for compressing and decompressing data using the GZip algorithm.

Let’s see an example of compressing a file named sample.txt:

string inputFile = @"C:\Users\username\Desktop\sample.txt";
string outputFile = @"C:\Users\username\Desktop\sample.txt.gz";

using (FileStream inputStream = File.OpenRead(inputFile))
{
    using (FileStream outputStream = File.Create(outputFile))
    {
        using (GZipStream gzipStream = new GZipStream(outputStream, CompressionLevel.Optimal))
        {
            inputStream.CopyTo(gzipStream);
        }
    }
}

In the above code, we first define the input and output file paths. We then open the input file in read mode using the File.OpenRead() method and create the output file in write mode using the File.Create() method.

We then create an instance of the GZipStream class, passing the output stream and the compression level as parameters. The CompressionLevel enumeration specifies the level of compression to be used, and it can have the following values: NoCompression, Fastest, Optimal.

We then copy the contents of the input stream to the GZip stream using the CopyTo() method.

The output file will be created in the specified path with the .gz extension.

Step 3: Decompressing a File

We can decompress a file using the same GZipStream class. Let’s see an example of decompressing a file named sample.txt.gz:

string inputFile = @"C:\Users\username\Desktop\sample.txt.gz";
string outputFile = @"C:\Users\username\Desktop\sample.txt";

using (FileStream inputStream = File.OpenRead(inputFile))
{
    using (FileStream outputStream = File.Create(outputFile))
    {
        using (GZipStream gzipStream = new GZipStream(inputStream, CompressionMode.Decompress))
        {
            gzipStream.CopyTo(outputStream);
        }
    }
}

In the above code, we first define the input and output file paths. We then open the input file in read mode using the File.OpenRead() method and create the output file in write mode using the File.Create() method.

We then create an instance of the GZipStream class, passing the input stream and the CompressionMode.Decompress mode as parameters.

We then copy the contents of the GZip stream to the output stream using the CopyTo() method.

The output file will be created in the specified path.

Step 4: Compressing a Folder

We can compress a folder by iterating over all the files in the folder and compressing each file individually.

Let’s see an example of compressing a folder named myfolder:

string folderPath = @"C:\Users\username\Desktop\myfolder";
string outputFile = @"C:\Users\username\Desktop\myfolder.zip";

using (FileStream zipStream = new FileStream(outputFile, FileMode.Create))
{
    using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
    {
        foreach (string file in Directory.GetFiles(folderPath))
        {
            string fileName = Path.GetFileName(file);
            archive.CreateEntryFromFile(file, fileName, CompressionLevel.Optimal);
        }
    }
}

In the above code, we first define the folder path and the output file path. We then create a new instance of FileStream class for the output file.

We then create a new instance of ZipArchive class, passing the output stream and the ZipArchiveMode.Create mode as parameters.

We then iterate over all the files in the folder using the Directory.GetFiles() method. For each file, we get its name using the Path.GetFileName() method and create a new entry in the archive using the CreateEntryFromFile() method, passing the file path, file name, and compression level as parameters.

The output file will be created in the specified path with the .zip extension.

Step 5: Decompressing a Folder

We can decompress a folder by iterating over all the entries in the archive and decompressing each entry individually. Let’s see an example of decompressing a folder named myfolder.zip:

string inputFile = @"C:\Users\username\Desktop\myfolder.zip";
string outputFolder = @"C:\Users\username\Desktop\myfolder_extracted";

using (ZipArchive archive = ZipFile.OpenRead(inputFile))
{
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        string outputPath = Path.Combine(outputFolder, entry.FullName);
        entry.ExtractToFile(outputPath);
    }
}

In the above code, we first define the input file path and the output folder path. We then create a new instance of ZipArchive class, passing the input file path as a parameter using the ZipFile.OpenRead() method.

We then iterate over all the entries in the archive using the Entries property. For each entry, we create the output path by combining the output folder path and the entry name using the Path.Combine() method.

We then extract the entry to the output path using the ExtractToFile() method.

The output folder will be created in the specified path, and all the files and subfolders will be extracted from it.

Conclusion:

In this tutorial, we learned how to use the System.IO.Compression namespace in C# to compress and decompress files and folders. We covered basic data compression concepts and provided examples of compressing and decompressing files and folders using the GZip and Zip compression algorithms.

Source(s): System.IO.Compression Namespace | Microsoft Learn