Prash's Blog

Compress and Uncompress in C# using .Net APIs December 3, 2012

Filed under: C# — prazjain @ 4:02 pm
Tags: , ,

Code snippet below for uncompressing a zip file to text file and compressing a text file back to zip file.
It is really minimal and I was able to uncompress 3+ gb text files using this, and as it just deals with stream you do not need to store the contents of the file in memory!
Here you go

        internal void UncompressZipFile(string fullPath, string zipPath)
        {
            //uncompress it
            Log.InfoFormat("Uncompressing XML zip file : Start");
            using (GZipStream gzs = new GZipStream(new FileStream(zipPath, FileMode.Open), CompressionMode.Decompress))
            {
                using (FileStream xmlFile = File.Create(fullPath))
                {
                    gzs.CopyTo(xmlFile);
                }
            }
            Log.InfoFormat("Uncompressing XML zip file : Finish");
        }

        internal void CompressCSVFile(string fullPath, string zipPath)
        {
            //Compress it
            Log.Info("Compressing CSV file : Start");
            using (FileStream csvFile = new FileStream(fullPath, FileMode.Open))
            {
                using (GZipStream gzs = new GZipStream(new FileStream(zipPath, FileMode.Create), CompressionMode.Compress))
                {
                    csvFile.CopyTo(gzs);
                }
            }
            Log.Info("Compressing CSV file : Finish");
        }