Saturday, June 28, 2008

Compressed Stream: GZipStream

With an increasing number of users for an application, an increase in bandwidth usage translates into increased costs for network connectivity. To reduce these costs, it is possible to compress some of the data being sent across. In ASP.NET, you can compress data that you write to a stream using the GZipStream and the DeflateStream classes. These classes are, from a develoepr's perspective, simply wrappers over the actual stream classes. You can use the Read and the Write methods to retrieve and store the data.

The difference between the GZipStream and DeflateStream classes is the GZip header added by the GZipStream - you can open a file written to by the GZipStream using a GZip decompression utility (WinRAR if you're on Windows, GUnZip if you're on *nix).

FileStream fs = File.Open("testfile1.gz", FileMode.OpenOrCreate, FileAccess.Write);
GZipStream gz = new GZipStream(fs, CompressionMode.Compress);
string txt = "Famous last words";
byte[] byteArr = System.Text.ASCIIEncoding.ASCII.GetBytes(txt);
gz.Write(byteArr, 0, byteArr.Length);

No comments: