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:
Post a Comment