Shalvin.Com                                                                                                                      Home

Compression in .Net

Two stream classes new to Framework 2.0 that supports compression are GZipStream and DeflateStream. Though both classes uses the same algorithm GZipStream is a better as it is compatible with tools like Gzip.

using System.IO;
using System.IO.Compression;

private void btnCompress_Click(object sender, EventArgs e)
{
  FileStream sourceFile = File.OpenRead( txtSource.Text);
  FileStream destFile = File.Create(txtDestination.Text);
  GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);
  int theByte = sourceFile.ReadByte();
  while (theByte != -1)
  {
    compStream.WriteByte((byte)theByte);
    theByte = sourceFile.ReadByte();
  }
sourceFile.Close();
destFile.Close();
}





Contact : shalvin@gmail.com