Monday, April 12, 2010

.Net C#: Compress / Decompress Methods

Utility Methods for data compression and data decompress.

using System.IO;
using System.IO.Compression;

public static byte[] Compress(byte[] bytes)
{
byte [] retValue;
using (MemoryStream stream = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Compress, true))
{
zipStream.Write(bytes, 0, bytes.Length);
retValue = stream.ToArray();
zipStream.Close();
stream.Close();
}
}
return retValue;
}


public static byte[] Decompress(byte[] bytes)
{
byte[] retValue;
using (MemoryStream stream = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress, true))
{
byte[] buffer = new byte[4096];
int size;
while (true)
{
size = zipStream.Read(buffer, 0, buffer.Length);
if (size > 0)
stream.Write(buffer, 0, size);
else
break;
}
zipStream.Close();
retValue = stream.ToArray();
stream.Dispose();
zipStream.Dispose();
return retValue;
}
}


No comments:

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge