Muflix
Muflix

Reputation: 6768

C# Decompress .GZip to file

I have this Code

using System.IO;
using System.IO.Compression;
...
UnGzip2File("input.gz","output.xls");

Which run this procedure, it runs without error but after it, the input.gz is empty and created output.xls is also empty. At the start input.gz had 12MB. What am i doing wrong ? Or have you better/functional solution ?

public static void UnGzip2File(string inputPath, string outputPath) 
        {
            FileStream inputFileStream = new FileStream(inputPath, FileMode.Create);
            FileStream outputFileStream = new FileStream(outputPath, FileMode.Create);

            using (GZipStream gzipStream = new GZipStream(inputFileStream, CompressionMode.Decompress))
            {
                byte[] bytes = new byte[4096];
                int n;

                // To be sure the whole file is correctly read, 
                // you should call FileStream.Read method in a loop, 
                // even if in the most cases the whole file is read in a single call of FileStream.Read method.

                while ((n = gzipStream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    outputFileStream.Write(bytes, 0, n);
                }
            }

            outputFileStream.Dispose();
            inputFileStream.Dispose();
        }

Upvotes: 0

Views: 3517

Answers (1)

Lorentz Vedeler
Lorentz Vedeler

Reputation: 5291

Opening the FileStream with the FileMode.Create will overwrite the existing file as documented here. This will cause the file to be empty when you try to decompress it, which in turn leads to an empty output-file.

Below is a working code sample, note that it is async, this can be changed by leaving out async/await and changing the call to the regular CopyTo-method and changing the return type to void.

public static async Task DecompressGZip(string inputPath, string outputPath)
{
    using (var input = File.OpenRead(inputPath))
    using (var output = File.OpenWrite(outputPath))
    using (var gz = new GZipStream(input, CompressionMode.Decompress))
    {
        await gz.CopyToAsync(output);
    }
}

Upvotes: 4

Related Questions