decompress a .gz file using GZipStream

Jun HU picture Jun HU · Jan 20, 2013 · Viewed 15.9k times · Source

I have several .gz files, and I want to decompress them one by one. I have writen a simple code using GzipStream in C#, but got failed. I wonder a correct and useful method to achieve what I want. Thanks a lot.

private string Extrgz(string infile)
{
    string dir = Path.GetDirectoryName(infile);
    string decompressionFileName = dir + Path.GetFileNameWithoutExtension(infile) + "_decompression.bin";
    using (GZipStream instream = new GZipStream(File.OpenRead(infile), CompressionMode.Compress))// ArgumentException...
    {
        using (FileStream outputStream = new FileStream(decompressionFileName, FileMode.Append, FileAccess.Write))
        {
            int bufferSize = 8192, bytesRead = 0;
            byte[] buffer = new byte[bufferSize];
            while ((bytesRead = instream.Read(buffer, 0, bufferSize)) > 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
            }
        }
    }
    return decompressionFileName;
}

Answer

Coder picture Coder · Jan 20, 2013

You need to decompress but you set CompressionMode.Compress, replace it with CompressionMode.Decompress.

Example here.