Compress byte array with GZip - CSharp System.IO.Compression

CSharp examples for System.IO.Compression:GZip

Description

Compress byte array with GZip

Demo Code


using System.IO;//from ww  w . jav  a  2  s. c o  m
using System.IO.Compression;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

public class Main{
        public static byte[] Compress(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
            zip.Write(buffer, 0, buffer.Length);
            zip.Close();
            ms.Position = 0;

            MemoryStream outStream = new MemoryStream();

            byte[] compressed = new byte[ms.Length];
            ms.Read(compressed, 0, compressed.Length);

            byte[] 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