omsharp
4/18/2015 - 4:53 PM

Simple GZip Compressing Utility.

Simple GZip Compressing Utility.

    public static class GZipper
    {
        private const int BUFFER_SIZE = 64 * 1024;

        public static byte[] Compress(byte[] data)
        {
            if (data == null)
                throw new ArgumentNullException("data", "data can't be null!");

            byte[] result;

            using (var compressMemStream = new MemoryStream())
            {
                using (var gZipStream = new GZipStream(compressMemStream, CompressionMode.Compress))
                {
                    using (var gZipBufferdStream = new BufferedStream(gZipStream, BUFFER_SIZE))
                    {
                        gZipBufferdStream.Write(data, 0, data.Length);
                    }
                }

                result = compressMemStream.ToArray();
            }

            return result;
        }

        public static byte[] Decompress(byte[] data)
        {
            if (data == null)
                throw new ArgumentNullException("data", "data can't be null!");

            byte[] result;

            using (var compressedMemStream = new MemoryStream(data))
            {
                using (var decompressMemStream = new MemoryStream())
                {
                    using (var gZipStream = new GZipStream(compressedMemStream, CompressionMode.Decompress))
                    {
                        using (var gZipBufferdStream = new BufferedStream(gZipStream, BUFFER_SIZE))
                        {
                            gZipBufferdStream.CopyTo(decompressMemStream);
                        }
                    }

                    result = decompressMemStream.ToArray();
                }
            }

            return result;
        }
    }