As many of you may know, .NET framework 2.0 contains a built in support for compressing the file or any generic stream such as FileStream, MemoryStream, TextWriter, XmlWriter, NetworkStream, etc

 

So, now, you can compress/decompress using GZip algorithm natively in .NET.  The code below is an example of compressing/decompressing a file.  To run it, create a C# Windows Application project, add a button to your form and create source.txt file with some text (e.g. Hello, World!) in c:\temp\compression folder.

 

private void button1_Click(object sender, EventArgs e)

{

    Compress(@"c:\temp\compression\source.txt", @"c:\temp\compression\compressed.txt");

    DeCompress(@"c:\temp\compression\compressed.txt", @"c:\temp\compression\result.txt");

}

 

private void Compress(string source, string destination)

{

    using (System.IO.FileStream sourceStream = System.IO.File.OpenRead(source))

    {

        using (System.IO.FileStream destinationStream = System.IO.File.OpenWrite(destination))

        {

            using (System.IO.Compression.GZipStream compressedStream = new System.IO.Compression.GZipStream(destinationStream, System.IO.Compression.CompressionMode.Compress))

            {

 

                byte[] data = new byte[sourceStream.Length];

                sourceStream.Read(data, 0, data.Length);

 

                compressedStream.Write(data, 0, data.Length);

            }

        }               

    }

}

 

private void DeCompress(string source, string destination)

{

    using (System.IO.FileStream sourceStream = System.IO.File.OpenRead(source))

    {

        using (System.IO.FileStream destinationStream = System.IO.File.OpenWrite(destination))

        {

            using (System.IO.Compression.GZipStream decompressedStream = new System.IO.Compression.GZipStream(sourceStream, System.IO.Compression.CompressionMode.Decompress))

            {

                // Note: decompressedStream.Length is not supported => results in runtime exception

                int data;

                while ((data = decompressedStream.ReadByte()) != -1)

                    destinationStream.WriteByte((byte)data);                       

            }

        }

    }

}