C#: Unzipping a gzip file

As part of Ring Veteran client, I was tasked to unizip some gzip files and came up with this working code I want to share:


         // Extracts the file contained within a GZip to the target dir.
         // A GZip can contain only one file, which by default is named the same as the GZip except
         // without the extension.
         public static List<String> Decompress(string gzipFileName, string targetDir) {
             var extracted = new List<String>();
             Debug.Log("Decompressing: "+ gzipFileName + " to: " + targetDir);
             // Use a 4K buffer. Any larger is a waste.    
             using (Stream fs = new FileStream(gzipFileName, FileMode.Open, FileAccess.Read)) {
                 using (var gzipStream = new GZipInputStream(fs)) {
                     // Change this to your needs
                     String fnOut = Path.Combine(targetDir, Path.GetFileNameWithoutExtension(gzipFileName));
                     Debug.Log("Extracting file: " + fnOut);
                     using (FileStream fsOut = File.Create(fnOut)) {
                         var dataBuffer = new byte[4096];
                         StreamUtils.Copy(gzipStream, fsOut, dataBuffer);
             return extracted;

Code returns a list of strings with the extracted file names. I use this to detect .tar files so I can expand those as well.


 public static void ExtractTar(String tarFileName, String destFolder) {
             Debug.Log("Decompressing: "+ tarFileName + " to: " + destFolder);
             Stream inStream = File.OpenRead(tarFileName);
             TarArchive tarArchive = TarArchive.CreateInputTarArchive(inStream);

SharpZipLib is required for this to work. As a note, make sure to compile the library with .Net 3.5 if you plan to use this with Unity3d ;).

 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Diagnostics;
 using ICSharpCode.SharpZipLib.Core;
 using ICSharpCode.SharpZipLib.GZip;
 using ICSharpCode.SharpZipLib.Tar;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s