How to compress dataset to byte array in C#

By FoxLearn 8/29/2024 7:16:10 AM   178
To compress a dataset into a byte array in C#, you can use various compression libraries available in .NET.

A commonly used library is System.IO.Compression, which provides classes for compression and decompression using GZip or Deflate algorithms.

How to compress dataset to byte array in C#

public static byte[] Compress(Dataset ds)
{
    using (var ms = new MemoryStream())
    {
        using (var gzip = new GZipStream(ms, CompressionMode.Compress, true))
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(gzip, ds);
        }
        return ms.ToArray();
    }
}

To compress dataset to byte array you can use GZipStream to compress the serialized byte array.

How to decompress byte array to dataset in C#

public static Dataset Decompress(byte[] data)
{
    using (var ms = new MemoryStream(data))
    {
        using (var gzip = new GZipStream(ms, CompressionMode.Decompress))
        {
            var formatter = new BinaryFormatter();
            return (Dataset)formatter.Deserialize(gzip);
        }
    }
}

To decompress the byte array to dataset, you need to decompress using GZipStream, and then deserialize back into a DataSet.

This example provides a simple way to compress and decompress a DataSet using built-in .NET libraries.