Compress a byte[] using GZip - CSharp System.IO.Compression

CSharp examples for System.IO.Compression:GZip

Description

Compress a byte[] using GZip

Demo Code


using System.IO.Compression;
using System.IO;/*w  w  w.  ja v a2s . c o m*/
using System;

public class Main{
        /// <summary>
        /// Compress a byte[].
        /// </summary>
        /// <param name="buffer">byte[] to be compressed.</param>
        /// <returns>byte array compressed.</returns>
        public static byte[] Compress(byte[] buffer)
        {
            var ms = new MemoryStream();

            var zip = new GZipStream(ms, CompressionMode.Compress, true);

            zip.Write(buffer, 0, buffer.Length);

            zip.Close();

            ms.Position = 0;

            var compressed = new byte[ms.Length];

            ms.Read(compressed, 0, compressed.Length);

            var gzBuffer = new byte[compressed.Length + 4];

            Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);

            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);

            return gzBuffer;
        }
}

Related Tutorials