Compressing and Decompressing Stream and Compression Techniques in .NET Framework

We can compress streams/data using two freely available methods:GZIP and DEFLATE. Unfortunately they are both limited to 4GB in size. The only difference is that GZIP allows for extra info in the header of the file.

GZipStream class inherits Stream class and has only one additional Property and all the methods are the same.


BaseStream Gets the underlying stream.

Here is an example of compression of one string into another. We require compressing destination stream before we can save data into it. We then write data into this compressed stream.
FileStream mySourceFile = File.OpenRead(inMyFilename);
FileStream myDestFile = File.Create(outMyFilename);
GZipStream myCompStream = new GZipStream(myDestFile, CompressionMode.Compress);
int theByte = mySourceFile.ReadByte();
while (theByte != -1)
    theByte = mySourceFile.ReadByte();


Decompression is quite similar and easy to understand from the example provided below.
FileStream mySourceFile = File.OpenRead(inFilename);
FileStream myDestFile = File.Create(outFilename);
GZipStream myCompStream = new GZipStream(myDestFile, CompressionMode.Decompress);
int theByte = myCompStream.ReadByte();
while (theByte != -1)
    theByte = myCompStream.ReadByte();

If we need to compress or decompress string without cyclic redundancy, we can use DEFLATE which takes three arguments: stream, compression mode and Boolean value to keep stream open or not. Cyclic redundancy is used for data corruption check and often assositated with GZipStream that can do that.