OWASP O2 Platform Blog

Decompressing HTTP GZIP responses using GZipStream (via extension methods)

Here is a good example of using Extension Methods to simplify the compressing and decompressing of strings.

This is how it is used:

var originalString = "this is the original string";

var compressedBytes = originalString.gzip_Compress();
var decompressedString = compressedBytes.gzip_Decompress();
return originalString == decompressedString; 
//O2File:_Extra_methods_Web.cs

Or even more simply:

return "this is a string".gzip_Compress().gzip_Decompress();
//O2File:_Extra_methods_Web.cs

Here is the source code of the gzip_Compress and gzip_Decompress Extension methods used above:

public static class _Extra_Web_ExtensionMethods_GZip
    {
        public static byte[] gzip_Compress(this string _string)
        {
            var bytes = Encoding.ASCII.GetBytes (_string);
            var outputStream = new MemoryStream();
            using (var gzipStream = new GZipStream(outputStream,CompressionMode.Compress))           
                gzipStream.Write(bytes, 0, bytes.size());           
            return outputStream.ToArray();
        }
       
        public static string gzip_Decompress(this byte[] bytes)
        {
            var inputStream = new MemoryStream();
            inputStream.Write(bytes, 0, bytes.Length);
            inputStream.Position = 0;
            var outputStream = new MemoryStream();
            using (var gzipStream= new GZipStream(inputStream,CompressionMode.Decompress))
            {
                byte[] buffer = new byte[4096];
                int numRead;
                while ((numRead = gzipStream.Read(buffer, 0, buffer.Length)) != 0)               
                    outputStream.Write(buffer, 0, numRead);               
            }   
            return outputStream.ToArray().ascii();
        }
    }

November 28, 2011 - Posted by | .NET

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: