Saturday, May 30, 2009

Compress/decompress byte array

// Compress/decompress byte array

using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
using System.Collections;

namespace Utilities
{
class Compression
{
public static byte[] Compress(byte[] data)
{
MemoryStream ms = new MemoryStream();
DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Write(data, 0, data.Length);
ds.Flush();
ds.Close();
return ms.ToArray();
}
public static byte[] Decompress(byte[] data)
{
const int BUFFER_SIZE = 256;
byte[] tempArray = new byte[BUFFER_SIZE];
List tempList = new List();
int count = 0, length = 0;

MemoryStream ms = new MemoryStream(data);
DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress);

while ((count = ds.Read(tempArray, 0, BUFFER_SIZE)) > 0)
{
if (count == BUFFER_SIZE)
{
tempList.Add(tempArray);
tempArray = new byte[BUFFER_SIZE];
}
else
{
byte[] temp = new byte[count];
Array.Copy(tempArray, 0, temp, 0, count);
tempList.Add(temp);
}
length += count;
}

byte[] retVal = new byte[length];

count = 0;
foreach (byte[] temp in tempList)
{
Array.Copy(temp, 0, retVal, count, temp.Length);
count += temp.Length;
}

return retVal;
}
}
}

1 comment:

  1. Dear Sir,

    I hope you are doing well. I got this email address from one of your contribution web site. I have launched a web site www.codegain.com and it is basically aimed C#,JAVA,VB.NET,ASP.NET,AJAX,Sql Server,Oracle,WPF,WCF and etc resources, programming help, articles, code snippet, video demonstrations and problems solving support. I would like to invite you as an author and a supporter.
    Looking forward to hearing from you and hope you will join with us soon.

    Thank you
    RRaveen
    Founder CodeGain.com

    ReplyDelete