Saturday, March 7, 2009

Compress Byte Arrays in .Net

This is some utility code I have been using to compress and decompress byte arrays using the .Net Framework’s compression classes. There are two compression classes available, GZipStream and DeflateStream, and they are found in the System.IO.Compression namespace. This example uses GZipStream. I did find a lot of examples on how to use the classes in relation to compressing file streams, but had to do a little more digging and experimenting to make it work with memory stream and byte arrays. I have found this code to be very useful in compressing items such as images for storage in a database. Though I haven’t tried it, it should work quite well in messaging scenarios too.

This example reads in a file, compresses data in memory, decompresses the data in memory and then writes the results out to a new file. Try your own file in the example. When it is completed, paste the contents of each file into NetDiff (a web based diff utility I wrote) to verify the files are identical.

Example:


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

namespace ConsoleZip
{
 class Program
 {
  static void Main(string[] args)
  {
   byte[] data = File.ReadAllBytes("c:\\test.log");
   byte[] compressed = Compress(data);
   byte[] decompressed = Decompress(compressed);
   File.WriteAllBytes("c:\\test2.log", decompressed);
 }

 static byte[] Compress(byte[] input)
 {
  using (MemoryStream output = new MemoryStream())
  {
   using (GZipStream zip = new GZipStream(output,CompressionMode.Compress) )
   {
    zip.Write(input, 0, input.Length);
   }
  return output.ToArray();
  }
 }

 static byte[] Decompress(byte[] input)
 {
  using (MemoryStream output = new MemoryStream(input))
  {
   using (GZipStream zip = new GZipStream(output, CompressionMode.Decompress))
   {
    List<byte> bytes = new List<byte>();
    int b = zip.ReadByte();
    while (b != -1)
    {
     bytes.Add((byte)b);
     b = zip.ReadByte();

    }
    return bytes.ToArray();
   }
  }
 
 }
}

3 comments:

Rocky said...

that was good one bro...
keep up the good work..
Regards
Rocky
idu2u.blogspot.com

james said...

I am always connect with friends through blogger.nice post Thanks for Sharing
More templates easy to download

rodex24 said...

Thanks for this Sir!
Nice compression technique.
Good help.