SoFunction
Updated on 2025-03-07

C# implementation of GZip compression and decompression

It is mainly because the first one of the constructors of GZipStream needs to pass in a Stream, and the second one is to specify the operation method: compression or decompression.

The main questions at that time were:

1. Is the Stream I passed in a Stream with uncompressed data?
2. When I decompress, do I read data from a compressed stream and then decompress it with GZipStream?

The above two questions arise, which is completely because I understand the usage of GZipStream incorrectly.

In fact, the GZipStream contains compressed data streams. The incoming Stream is passed in as the basic Stream. If you want to compress, you can pass an empty Stream in. If you want to decompress, you can pass the Stream containing the compressed data in.

The read and write of GZipStream correspond to the two operations of decompression and compression. Knowing these, it is easy to use.

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

Copy the codeThe code is as follows:

byte[] cbytes = null;
//compression
            using (MemoryStream cms = new MemoryStream())
            {
                using ( gzip = new (cms,))
                {
//Write data to the underlying stream and will be compressed at the same time
byte[] bytes = Encoding.("Decompression test");
                    (bytes, 0, );
                }
                cbytes = ();
            }
//Decompression
            using (MemoryStream dms = new MemoryStream())
            {
                using (MemoryStream cms = new MemoryStream(cbytes))
                {
                    using ( gzip = new (cms, ))
                    {
                        byte[] bytes = new byte[1024];
                        int len = 0;
//Read the compressed stream and will be decompressed at the same time
                        while ((len = (bytes, 0, )) > 0)
                        {
                            (bytes, 0, len);
                        }
                    }
                }
                (Encoding.(()));
            }

At the same time, the stream passed in during compression can be a non-empty stream. You can write the compressed data after writing other data, which will not affect the final result.

If you encounter the prompt "magic number header is incorrect" when decompressing, it is because the data you want to decompress is not compressed with GZip.