Friday, January 04, 2008

How to compress/uncompress string in .net before passing it over the network?

If you want to compress string before passing it over the network to save bandwidth or uncompress it back here is the code for the same. It usese freeware NZIPLIB library. You can download the source code and compiled assembly from this site. Download now!

using System;
using NZlib.GZip;
using NZlib.Compression;
using NZlib.Streams;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Xml;
namespace zipper
{
public class MyClass
{
public static string Compress(string uncompressedString)
{
byte[] bytData = System.Text.Encoding.UTF8.GetBytes(uncompressedString);
MemoryStream ms = new MemoryStream();
Stream s = new DeflaterOutputStream(ms);
s.Write(bytData, 0, bytData.Length);
s.Close();
byte[] compressedData = (byte[])ms.ToArray();
return System.Convert.ToBase64String(compressedData, 0, _
compressedData.Length);
}

public static string DeCompress(string compressedString)
{
string uncompressedString="";
int totalLength = 0;
byte[] bytInput = System.Convert.FromBase64String(compressedString);;
byte[] writeData = new byte[4096];
Stream s2 = new InflaterInputStream(new MemoryStream(bytInput));
while (true)
{
int size = s2.Read(writeData, 0, writeData.Length);
if (size > 0)
{
totalLength += size;
uncompressedString+=System.Text.Encoding.UTF8.GetString(writeData, _
0, size);
}
else
{
break;
}
}
s2.Close();
return uncompressedString;
}
}
}

No comments: