C implements the GZip compression and decompression entry example

  • 2020-06-19 11:37:02
  • OfStack

This is mainly because the first one in GZipStream's constructor needs to pass in one Stream, and the second one specifies whether to compress or decompress.

The main questions at that time were:

1. Is the Stream I pass in Stream containing uncompressed data?
2. Do I read data from one compression stream before extracting with GZipStream?

The above two questions are completely because I understand the usage of GZipStream backwards.

In fact, what is stored in GZipStream is the compressed data stream, and the incoming Stream is passed in as the basic Stream. If you want to compress, you can pass in an empty Stream, and if you want to uncompress, you can pass in the Stream containing the compressed data.

GZipStream's read and write operations correspond to decompression and compression, respectively, which makes it easy to use.

The data written will be compressed and written to the incoming Stream, and the data read will also be decompressed and can be written directly to a new stream.


byte[] cbytes = null;
// The compression 
            using (MemoryStream cms = new MemoryStream())
            {
                using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(cms,System.IO.Compression.CompressionMode.Compress))
                {
                    // Write the data to the underlying stream and it will be compressed 
                    byte[] bytes = Encoding.UTF8.GetBytes(" Decompression test ");
                    gzip.Write(bytes, 0, bytes.Length);
                }
                cbytes = cms.ToArray();
            }
// Unpack the 
            using (MemoryStream dms = new MemoryStream())
            {
                using (MemoryStream cms = new MemoryStream(cbytes))
                {
                    using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(cms, System.IO.Compression.CompressionMode.Decompress))
                    {
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        // Read the compression stream and it will be decompressed 
                        while ((len = gzip.Read(bytes, 0, bytes.Length)) > 0)
                        {
                            dms.Write(bytes, 0, len);
                        }
                    }
                }
                Console.WriteLine(Encoding.UTF8.GetString(dms.ToArray()));
            }

At the same time, the incoming stream can be a non-empty stream, and you can write the compressed data after writing other data without affecting the final result.

If you encounter an "incorrect magic head" message when decompressing, it is because the data you are decompressing is not compressed using GZip.


Related articles: