Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


GZip byte array using System.IO.Compression in .NET
Here is how to compress/uncompress a byte array using .NET's GZip ability:

public static class CompressionHelper
{
/// <summary>
/// Compress the byte[]
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static byte[] Compress(byte[] input)
{
byte[] output;
using (MemoryStream ms = new MemoryStream())
{
using(GZipStream gs = new GZipStream(ms, CompressionMode.Compress))
{
gs.Write(input, 0, input.Length);
gs.Close();
output = ms.ToArray();
}
ms.Close();
}
return output;
}

/// <summary>
/// Decompress the byte[]
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static byte[] Decompress(byte[] input)
{
List<byte> output = new List <byte> ();
using (MemoryStream ms = new MemoryStream(input))
{
using (GZipStream gs = new GZipStream(ms, CompressionMode.Decompress))
{
int readByte = gs.ReadByte();
while(readByte != -1)
{
output.Add((byte)readByte);
readByte = gs.ReadByte();
}
gs.Close();
}
ms.Close();
}
return output.ToArray();
}
} // class

Created By: amos 7/30/2009 6:40:28 PM
Updated: 4/2/2013 2:55:58 PM


 Comments:
 > Guest 6/17/2011 12:25:30 AM
It is very useful
 > Guest 6/22/2011 6:58:49 AM
The last 4 bytes of a gzipped file, is an integer containing the size of the uncompressed data. You can use that, to initialize a byte array first, and use that instead of a list, for making it more efficient.
 > Guest 10/15/2012 3:33:20 PM
FODASTICO!!!
 > Guest 3/15/2013 7:50:54 AM
Saved my life., tks.
 > Guest 6/1/2013 6:44:34 AM
nice work
 > Guest 1/31/2014 6:13:25 AM
Thanks a lot.
It works fine.
 > Guest 8/8/2015 12:11:38 AM
Thanks for sharing - this is really helpful