« Back to blog

Write dataset contents to zip file

Assume that you want to write the contents of a dataset to xml, in order to send that data via e-mail or any other means. Have you noticed how verbose xml files are? However, if you try to compress one, you will notice that size of the compressed file is only a small fragment of the original! Just for testing, I compressed an 200MB XML file into a zip file, to see that the resulting file was 9MB only!
So, is it possible to write the contents of a dataset into an xml but include that xml directly into a zip file, without even creating a temporary file? Yes it is! Here is how. Note that the following code uses SharpZipLib, an open source Zip, GZip, Tar and BZip2 library.

        ' create a sample dataset
        Dim data As New DataSet
        ' TODO : add code that fills the dataset here

        ' create a zip output stream
        Dim FileStream As IO.FileStream = System.IO.File.Create("c:\output.zip")
        Using ZipOutputStream As New Zip.ZipOutputStream(FileStream)
            ZipOutputStream.SetLevel(9) ' maximum compression level

            ' create a new empty entry in zip file
            ' myData.xml will be the name of the xml file inside the zip
            Dim objZipEntry As New Zip.ZipEntry("myData.xml")
            ZipOutputStream.PutNextEntry(objZipEntry)

            ' write dataset to zip stream
            data.WriteXml(ZipOutputStream)
        End Using

Click here to download:
Dataset2Zip._zip (86 KB)

Uses : Visual Studio 2005, VB8

Comments (0)

Leave a comment...