Skip to content

Instantly share code, notes, and snippets.

@wasimf
Created September 1, 2013 10:23
Show Gist options
  • Save wasimf/6403527 to your computer and use it in GitHub Desktop.
Save wasimf/6403527 to your computer and use it in GitHub Desktop.
CompressionService - .Net Gzip based compression service .
byte[] buffer = Encoding.UTF8.GetBytes(text);
var ms = new MemoryStream();
using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
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 Convert.ToBase64String(gzBuffer);
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (var ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (var zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment