12 August 2018
Categories: Software Development
Posted in: C#, .NET, GZIP
Goals
G-Zip compression using C#
This article will teach you how to compress and decompress data with G-Zip using C# and .NET
For more information regarding G-Zip please visit: https://www.gzip.org
The following class will compress and decompress data using the G-Zip algorythm:
public static class GZipCompressor
{
public static byte[] GZipCompress(byte[] source)
{
using (var outStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(outStream, CompressionMode.Compress))
{
using (var ms = new MemoryStream(source))
{
ms.CopyTo(gzipStream);
}
}
return outStream.ToArray();
}
}
public static byte[] GZipDecompress(byte[] compressed)
{
using (var inStream = new MemoryStream(compressed))
{
using (var gzipStream = new GZipStream(inStream, CompressionMode.Decompress))
{
using (var ms = new MemoryStream())
{
gzipStream.CopyTo(ms);
return ms;
}
}
}
}
}
If your source data type is 'string', you can get a byte array with Encoding.UTF8.GetBytes(myString). To convert a byte array back to a string you can use Encoding.UTF8.GetString(ms.ToArray())
Here's a variation of the above class that will compress/decompress strings:
public static class GZipCompressor
{
public static byte[] GZipCompress(string inputString)
{
using (var outStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(outStream, CompressionMode.Compress))
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(inputString)))
{
ms.CopyTo(gzipStream);
}
}
return outStream.ToArray();
}
}
public static string GZipDecompress(byte[] compressed)
{
using (var inStream = new MemoryStream(compressed))
{
using (var gzipStream = new GZipStream(inStream, CompressionMode.Decompress))
{
using (var ms = new MemoryStream())
{
gzipStream.CopyTo(ms);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
}
}
Happy Coding! ;)