Ed.
Ed.

Reputation: 1694

Unzipping a .gz file using C#

I have a tarred gunzip file called ZippedXmls.tar.gz which has 2 xmls inside it. I need to programmatically unzip this file and the output should be 2 xmls copied in a folder.

How do I achieve this using C#?

Upvotes: 18

Views: 29531

Answers (4)

bobt
bobt

Reputation: 585

This works for me.

using ICSharpCode.SharpZipLib.GZip;

// Specify the path to the input and output files
string inputFile = "input.gz";
string outputFile = "output.txt";

// Open the input file for reading
using (FileStream inputStream = new FileStream(inputFile, FileMode.Open))
{
    // Create a GZipInputStream to decompress the input file
    using (GZipInputStream gzipStream = new GZipInputStream(inputStream))
    {
        // Open the output file for writing
        using (FileStream outputStream = new FileStream(outputFile, FileMode.Create))
        {
            // Copy the decompressed data from the GZipInputStream to the output file
            gzipStream.CopyTo(outputStream);
        }
    }
}

Upvotes: 0

Lee Richardson
Lee Richardson

Reputation: 8827

I know this question is ancient, but search engines redirect here for how to extract gzip in C#, so I thought I'd provide a slightly more recent example:

using (var inputFileStream = new FileStream("c:\\myfile.xml.gz", FileMode.Open))
using (var gzipStream = new GZipStream(inputFileStream, CompressionMode.Decompress))
using (var outputFileStream = new FileStream("c:\\myfile.xml", FileMode.Create))
{
    await gzipStream.CopyToAsync(outputFileStream);
}

For what should be the simpler question of how to untar see: Decompress tar files using C#

Upvotes: 3

Charlie Salts
Charlie Salts

Reputation: 13488

I've used .Net's built-in GZipStream for gzipping byte streams and it works just fine. I suspect that your files are tarred first, before being gzipped.

You've asked for code, so here's a sample, assuming you have a single file that is zipped:

FileStream stream = new FileStream("output.xml", FileMode.Create); // this is the output
GZipStream uncompressed = new GZipStream(stream, CompressionMode.Decompress);

uncompressed.Write(bytes,0,bytes.Length); // write all compressed bytes
uncompressed.Flush();
uncompressed.Close();

stream.Dispose();

Edit:

You've changed your question so that the file is a tar.gz file - technically my answer is not applicable to your situation, but I'll leave it here for folks who want to handle .gz files.

Upvotes: 35

Stefan Egli
Stefan Egli

Reputation: 17018

sharpziplib should be able to do this

Upvotes: 7

Related Questions