Compressing and Decompressing files in C#.Net

In this tutorial I am trying to show the usage of .Net library to compress and decompress files.

GZipStream

We are using the class from namespace System.IO.Compression.

Basically the example, loads a text file compresses it into a file.

Compressing

private void Compress(string originalFile, string destinationFile)

{

    FileStream inStream = new FileInfo(originalFile).OpenRead();

    FileStream fileStream = File.Create(destinationFile);

    GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Compress);

 

    byte[] buffer = new byte[4096];

    int numRead;

    while ((numRead = inStream.Read(buffer, 0, buffer.Length)) != 0)

    {

        gzipStream.Write(buffer, 0, numRead);

    }

 

    gzipStream.Dispose();

    fileStream.Dispose();

    inStream.Dispose();

}

Decompressing

private void Decompress(string compressedFile, string destinationFile)

{

    FileStream compressedStream = new FileInfo(compressedFile).OpenRead();

    FileStream destinationStream = File.Create(destinationFile);

    GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress);

    byte[] buffer = new byte[4096];

 

    int numRead;

 

    while ((numRead = gzipStream.Read(buffer, 0, buffer.Length)) != 0)

    { 

        destinationStream.Write(buffer, 0, numRead); 

    }

 

    gzipStream.Dispose();

    destinationStream.Dispose();

    compressedStream.Dispose();

}

Leave a Reply

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