GZipStream class
Provides methods and attributes for compressing and extracting streams.
This class represents the GZip data format, which uses industry-standard algorithms for lossless compression and decompression of files. This format includes a cyclic redundancy check value that detects data corruption. GZip uses the same algorithm as DeflateStream, but it can be extended to use other compression formats. This format can be easily implemented in a way that does not involve the right to use a patent. The Gzip format can be obtained from RFC 1952 GZIP file format specification 4.3 (GZIP file format specification 4.3. This class cannot be used to compress files larger than 4 GB.
// Compress data
Static Byte [] Compress (Byte [] data)
{
// Compress the data into this memory stream
Using (MemoryStream target = new MemoryStream ())
{
Using (GZipStream gs = new GZipStream (target, CompressionMode. Compress, true ))
{
// Write data to the compressed stream
Gs. Write (data, 0, data. Length );
}
Return target. ToArray ();
}
}
// Decompress the data
Static Byte [] DeCompress (Byte [] data)
{
Using (MemoryStream source = new MemoryStream ())
{
Using (GZipStream gs = new GZipStream (new MemoryStream (data), CompressionMode. Decompress, true ))
{
// Read all data from the compressed stream
Byte [] bytes = new byte [1, 4096];
Int n;
While (n = gs. Read (bytes, 0, bytes. Length ))! = 0)
{
Source. Write (bytes, 0, n );
}
}
Return source. ToArray ();
}
}
Static string GetTestString ()
{
StringBuilder builder = new StringBuilder ();
For (int I = 0; I <1000; I ++)
Builder. Append ("I Am a test data ");
Return builder. ToString ();
}
String test = GetTestString ();
Byte [] original = Encoding. Default. GetBytes (test );
Console. WriteLine ("the original data length is:" + original. LongLength. ToString ());
Byte [] compressed = Compress (original );
Console. WriteLine ("the compressed data length is:" + compressed. LongLength );
Byte [] back = DeCompress (compressed );
Console. WriteLine ("extract and obtain the Data Length:" + back. LongLength. ToString ());
Console. WriteLine ("Equal before and after decompression:" + test. Equals (Encoding. Default. GetString (back )));