Simple GZip compression of files with .NET


I had to do some file compression recently (which oddly enough I had never had to do before).  

Compressing files using GZipStream in a few lines of code:

using (FileStream fStream = 
new FileStream(@"C:\test.docx.gzip", FileMode.Create, FileAccess.Write))
{
using (GZipStream zipStream = new GZipStream(fStream, CompressionMode.Compress))
{
byte[] inputfile = File.ReadAllBytes(@"c:\test.docx");
zipStream.Write(inputfile, 0, inputfile.Length);
}
}

Decompressing is also quite simple:

using (FileStream fInStream = 
new
FileStream(@"c:\test.docx.gz", FileMode.Open, FileAccess.Read))
{
using (GZipStream zipStream = new GZipStream(fInStream, CompressionMode.Decompress))
{
using (FileStream fOutStream =
new
FileStream(@"c:\test1.docx", FileMode.Create, FileAccess.Write))
{
byte[] tempBytes = new byte[4096];
int i;
while ((i = zipStream.Read(tempBytes, 0, tempBytes.Length)) != 0)
{
fOutStream.Write(tempBytes, 0, i);
}
}
}
}
Comments (3)
  1. Anthony Parry says:

    Dead useful – thanks very much. (Converted into a Powershell script.)

  2. Arjun says:

    please help me with this.. how do i unzip the password protected .zip file using gzip

  3. Albert says:

    Thanks boet, that helped a lot.

    bert

Comments are closed.

Skip to main content