Friday, February 25, 2011

Compressing and Decompressing Dataset in C#



Some times we need to Compress the Dataset, if it holds large data, before sending over network. If you are using web services or WCF Services ,It is better to compress the dataset to byte array before sending over the network. You can decompress the byte array to dataset. Here is some code snippet to do that using System.IO.Compression.


   1:  using System;
   2:  using System.IO;
   3:  using System.Data;
   4:  using System.IO.Compression;
   5:   
   6:  namespace TestApp
   7:  {
   8:      public class DataSetCompressor
   9:      {
  10:   
  11:          public Byte[] Compress(DataSet dataset) 
  12:          { 
  13:              Byte[] data; 
  14:              MemoryStream mem = new MemoryStream(); 
  15:              GZipStream zip = new GZipStream(mem, CompressionMode.Compress); 
  16:              dataset.WriteXml(zip, XmlWriteMode.WriteSchema);
  17:              zip.Close();
  18:              data = mem.ToArray();
  19:              mem.Close(); 
  20:              return data; 
  21:          }          
  22:          public DataSet Decompress(Byte[] data) 
  23:          { 
  24:              MemoryStream mem = new MemoryStream(data);
  25:              GZipStream zip = new GZipStream(mem, CompressionMode.Decompress); 
  26:              DataSet dataset = new DataSet(); 
  27:              dataset.ReadXml(zip, XmlReadMode.ReadSchema); 
  28:              zip.Close();
  29:              mem.Close();
  30:              return dataset;
  31:          }
  32:      }
  33:  }

5 comments:

  1. Hi GooD Effort To Others...

    ReplyDelete
  2. Hi Sebastian,

    Your article is simple and useful.

    ReplyDelete
  3. Thanks Sebastian this is the cleanest and best example.

    ReplyDelete
  4. Has error when decompress: The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.

    ReplyDelete
    Replies
    1. Yes there is error on decompress, how to fix?

      Delete