Freigeben über


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

  • Anonymous
    December 11, 2008
    Dead useful - thanks very much. (Converted into a Powershell script.)

  • Anonymous
    May 05, 2009
    please help me with this.. how do i unzip the password protected .zip file using gzip

  • Anonymous
    March 05, 2010
    Thanks boet, that helped a lot. bert