Friday, 21 May 2010

Compress and de-compress strings in C#

A collection of resources on compressing and encrypting strings in C#.
Microsoft documentation on the System.IO.Compression.GZipStream class:
http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx
Helpful example class utilising GZip:
http://www.csharphelp.com/2007/09/compress-and-decompress-strings-in-c/
The GZipStream class is predominantly used for file compression but can be used efficiently for compressing strings of 300-400 characters or more. Below 300 characters there isn’t any measurable gain from the compression and for particularly short strings the compressed version may in fact be larger.
Class provided by C Sharp Help:
using System.IO.Compression;
using System.Text;
using System.IO;

public static string Compress(string text)
{
    byte[] buffer = Encoding.UTF8.GetBytes(text);
    MemoryStream ms = new MemoryStream();
    using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
    {
        zip.Write(buffer, 0, buffer.Length);
    }

    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];
    System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
    System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
    return Convert.ToBase64String (gzBuffer);
}

public static string Decompress(string compressedText)
{
    byte[] gzBuffer = Convert.FromBase64String(compressedText);
    using (MemoryStream 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 (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
        {
            zip.Read(buffer, 0, buffer.Length);
        }

        return Encoding.UTF8.GetString(buffer);
    }
}

No comments: