tsJensen

A quest for software excellence...

SharpZipLib and Kudos to Scott Galloway

I had to get an object serialized to a byte[] and then compress it using SharpZipLib and gzip and then decompress it and deserialize it to the original object. The serialization was easy but for some reason I was struggling with using the GZipOutputStream and GZipInputStream compression providers in the SharpZipLib library.

Then I found Scott Galloway's compression helper. I highly recommend it. Anyway, here's the code without the helper. Visit Scott's blog for that.

 public class ResultSerializer
 {
  public static byte[] Serialize(ResultData data)
  {
   //convert to byte[]
   IFormatter frm = new BinaryFormatter();
   MemoryStream ms = new MemoryStream(8096);
   frm.Serialize(ms, data);
   byte[] serial = ms.ToArray();
   ms.Close();
   byte[] retval = ZipUtil.Compress(serial);
   return retval;
  }
  public static ResultData Deserialize(byte[] zipData)
  {
   byte[] data = ZipUtil.DeCompress(zipData);
   //now deserialize
   IFormatter frm = new BinaryFormatter();
   MemoryStream datams = new MemoryStream(data, 0, data.Length);
   ResultData retval = (ResultData)frm.Deserialize(datams);
   return retval;
  }
 }

Note that I renamed Scott's helper "ZipUtil" for my own reasons.