November 28, 2006

Compression and Decompression (Using .NET 2005 - GZipStream)

Points to be consider:

1. Make sure size of string is appropiate before performing compression. Less size (approx string.Length <1000>

2. Use ToBase64String() and FromBase64String() for passing string using webservice or pass bytes.


using System;
using System.IO;
using System.IO.Compression;
using System.Text;
public class GZipCode {
public static void Main(string[] args) {
byte[] compressedBytes = CompressString("string to compress");
string ss = DeCompressBytes(compressedBytes);
Console.WriteLine(ss);
}
///


/// Decompress given bytes and return string
///

/// Bytes to uncompress
/// Uncompressed string
internal static string DeCompressBytes(byte[] CompressedBytes) {
MemoryStream stream = new MemoryStream();
// Decompress bytes using GZipStream
GZipStream gZipStream = new GZipStream(new MemoryStream(CompressedBytes), CompressionMode.Decompress);
// read stream
byte[] buffer = new byte[4096];
while (true) {
int bytesRead = gZipStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
stream.Write(buffer, 0, bytesRead);
else {
if (stream.Length == 0)
throw new Exception("Cannot read from GZipStream.");
else
break;
}
}
gZipStream.Close();
return Encoding.ASCII.GetString(stream.ToArray());
}
///
/// Compress given string and return bytes
///

/// String to compress
/// Compressed bytes
internal static byte[] CompressString(string StringToCompress) {
MemoryStream ms = new MemoryStream();
// conevrt string in byte array
byte[] BytesToCompress = Encoding.ASCII.GetBytes(StringToCompress);
// compress bytes
GZipStream compressedZipStream = new GZipStream(ms, CompressionMode.Compress, true);
compressedZipStream.Write(BytesToCompress, 0, BytesToCompress.Length);
compressedZipStream.Close();
// return byte array
return ms.ToArray();
}
}