Wednesday, November 23, 2011

Compressing and Decompressing Text Strings using GZipStream

Simply wanted to pass a text to client and the receive it back again. Something like the old viewstate concept. I searched the web for ready to use piece of code that compress the text into byte[] and vice versa but I failed to find a working source code, so I wrote one.

Here it is:

public class Zip
    //public static Encoding Encoding = System.Text.Encoding.Unicode;
    public static byte[] Compress(string text, Encoding Encoding = null)
        if (text == nullreturn null;
        Encoding = Encoding ?? System.Text.Encoding.Unicode;            // If the encoding is not specified use the Unicode
        var textBytes = Encoding.GetBytes(text);                        // Get the bytes according to the encoding
        var textStream = new MemoryStream();                            // Make a stream of to be feeded by zip stream
        var zip = new GZipStream(textStream, CompressionMode.Compress); // Create a zip stream to receive zipped content in textStream
        zip.Write(textBytes, 0, textBytes.Length);                      // Write textBytes into zip stream, then zip will populate textStream
        return textStream.ToArray();                                    // Get the bytes from the text stream
    public static string Decompress(byte[] value, Encoding Encoding = null)
        if (value == nullreturn null;
        Encoding = Encoding ?? System.Text.Encoding.Unicode;                // If the encoding is not specified use the Uncide
        var inputStream = new MemoryStream(value);                          // Create a stream based on input value
        var outputStream = new MemoryStream();                              // Create a stream to recieve output
        var zip = new GZipStream(inputStream, CompressionMode.Decompress);  // Create a stream to decompress inputStream into outputStream
        byte[] bytes = new byte[4096];
        int n;
        while ((n = zip.Read(bytes, 0, bytes.Length)) != 0)                 // While zip results output bytes from input stream
            outputStream.Write(bytes, 0, n);                                // Write the unzipped bytes into output stream
        return Encoding.GetString(outputStream.ToArray());                  // Get the string from unzipped bytes


  1. When coding this and trying to execute, I get a Cannot Access a closed stream message by the return textStream.ToArray() line.
    This because the zip.Close() has already been done, the textStream is also freed...