Just Code‎ > ‎

C# - Gzip Uncompress and Compress Example using System.IO.Compression.GZipStream

posted May 11, 2012, 1:44 AM by Peter Henell   [ updated May 11, 2012, 1:45 AM ]
Sometimes it is a good idea to compress some data that you manage in a system. 
If you are managing compress data in the system it will end up as arrays of bytes. To make it easier to work with it you can convert it to a string using 
System.Convert.ToBase64String
and then back to byte array using 
System.Convert.FromBase64String
using System.Text;
using System.IO;
using System.IO.Compression;
using System;

namespace Decrompressor
{
    public class GZipManager
    {
        public static string Deccompress(byte[] byteArray)
        {
            StringBuilder uncompressed = new StringBuilder();

            using (MemoryStream memoryStream = new MemoryStream(byteArray))
            {
                using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    byte[] buffer = new byte[1024];

                    int readBytes;
                    while ((readBytes = gZipStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        for (int i = 0; i < readBytes; i++)
                            uncompressed.Append((char)buffer[i]);
                    }
                }

                return uncompressed.ToString();
            }
        }

        public static byte[] Compress(string text, Encoding encoding = null)
        {
            if (string.IsNullOrEmpty(text))
                throw new ArgumentException("text cannot be null nor empty"); 

            encoding = encoding ?? System.Text.Encoding.Unicode;            
            byte[] inputBytes = encoding.GetBytes(text);                        
            using (MemoryStream resultStream = new MemoryStream())
            {
                using (GZipStream gZipStream = new GZipStream(resultStream, CompressionMode.Compress))
                {
                    gZipStream.Write(inputBytes, 0, inputBytes.Length);
                    return resultStream.ToArray();
                }
            }
                                                
        }

    }
}

Comments