GZipStream Class

Overview

  • Used to compress and decompress data.
  • Slightly larger result than DeflateStream because of extra header information.
  • Use for files that need to be able to be opened with gzip.
  • Works like a BufferedStream as it sits on top of another stream.
  • Limited to files up to 4GB (uncompressed).

Good practice

  • Remember to call Close on a stream.

Examples

Compress File

FileStream fileIn = File.OpenRead(@"C:\Public\Test.txt");
FileStream fileOut = File.OpenWrite(@"C:\Public\TestComp.txt");
 
GZipStream compress = new GZipStream(fileOut, CompressionMode.Compress);
 
byte[] buffer = new byte[fileIn.Length];
fileIn.Read(buffer, 0, buffer.Length);
compress.Write(buffer, 0, buffer.Length);
compress.Close();
 
fileIn.Close();
fileOut.Close();

Decompress File

FileStream compressedFile = File.OpenRead(@"C:\Public\TestComp.txt");
GZipStream decompress = new GZipStream(compressedFile, CompressionMode.Decompress);
StreamReader read = new StreamReader(decompress);
 
Console.WriteLine(read.ReadToEnd());
read.Close();
decompress.Close();
compressedFile.Close();