Compressing and Decompressing files using GZIP Format in C#

To compress and decompress files using GZIP Format, use the GZipStream class.


To zip a file, use the GZipStream class with the FileStream class. Set the following parameters.

File to be zipped and the name of the output zip file.

Here, outputFile is the output file and the file is read into the FileStream.


using(var compress = new GZipStream(outputFile, CompressionMode.Compress, false)) {
   byte[] b = new byte[inFile.Length];
   int read = inFile.Read(b, 0, b.Length);
   while (read > 0) {
      compress.Write(b, 0, read);
      read = inFile.Read(b, 0, b.Length);


To decompress a file, use the same the GZipStream class. Set the following parameters: source file and the name of the output file.

From the source zip file, open a GZipStream.

using (var zip = new GZipStream(inStream, CompressionMode.Decompress, true))

To decompress, use a loop and read as long as you have data in the stream. Write it to the output stream and a file generates. The file is our decompressed file.


using(var zip = new GZipStream(inputStream, CompressionMode.Decompress, true)) {
   byte[] b = new byte[inputStream.Length];
   while (true) {
      int count = zip.Read(b, 0, b.Length);
      if (count != 0)
      outputStream.Write(b, 0, count);
      if (count != b.Length)
Samual Sam
Samual Sam

Learning faster. Every day.