Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Converting and Compressing a Dataset to Byte array

4.88/5 (8 votes)
24 Jan 2011CPOL 36.6K  
Convert a Dataset to bytes array and then compress that array.
Hello everybody,
Hope everyone is fine. This is my first article/tip on CodeProject. Pardon me for any mistakes or rule violations. Thanks.

Introduction

There are a number of occasions when we have to pass datatable/Dataset from a web service to some other webservice or application. I will show you how to convert the dataset to an array of bytes and then compress that array so that the overall procedure becomes more efficient and optimized.

Namespaces

The namespace you will have to add in order to get this thing working are:
System.IO.Compression
System.IO

Convert and Compress Dataset to Bytes array

This function will take a dataset as argument and converts the dataset to a byte array and then compresses it.
VB
Public Function CompressData(ByVal ds As DataSet) As Byte()
        Try
            Dim data As Byte()
            Dim memStream As New MemoryStream()
            Dim zipStream As GZipStream = New GZipStream(memStream, CompressionMode.Compress)
            ds.WriteXml(zipStream, XmlWriteMode.WriteSchema)
            zipStream.Close()
            data = memStream.ToArray()
            memStream.Close()
            Return data
        Catch ex As Exception
            Return Nothing
        End Try
    End Function


Convert and Decompress Byte array to Dataset

Now the reciprocal of the above function. This function will decompress the bytes array received and converts it back to the dataset.

VB
Public Function DecompressData(ByVal data As Byte()) As DataSet
        Try
            Dim memStream As New MemoryStream(data)
            Dim unzipStream As New GZipStream(memStream, CompressionMode.Decompress)
            Dim objDataSet As New DataSet()
            objDataSet.ReadXml(unzipStream, XmlReadMode.ReadSchema)
            unzipStream.Close()
            memStream.Close()
            Return objDataSet
        Catch ex As Exception
            Return Nothing
        End Try
    End Function


Conclusion

If you have to transfer/recieve Dataset/Datatable between webservices or web Applications, this would be a good idea to convert your dataset to a byte array and then compress the byte array. In this way, the whole procedure will be more optimized.

Hope this article was helpful.

Ahsan Sarfraz
Software Engineer
Pakistan

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)