Back to Basics – Zip in .NET
In my current project we save Xml data in our database. The field to
save the data was of type varchar(6000). This way of saving the data raised
a problem of big Xml data (over 8000 kb for every Xml data)
which were saved in the database and for the long run could raise
space and performance problems.
Use the compression abilities of .NET framework, compress the
Xml data and save the data in a binary form. We needed to change the
field type in the database to binary type and compress the Xml data
before inserting it to the database. After the binary data was retrieved
from the database a reverse process of decompress returns the
original Xml string.
I first built a console application to write the code and test it.
Then, I wired the zip and unzip methods I wrote to the part that needed
the compression. The following code is the console application’s
zip and unzip methods I used to compress the Xml data.
Some things that should be concerned if you are going to use this code:
- The encoding of the strings I use are in UTF8 format. If you use other
formats you should change the Encoding.UTF8 code to the format you
- In the decompress process I use a fixed array of 4096 bytes. This is only
for the testing application in the real method I save the original size of
Lets sum up, I used a compression method to compress Xml data in the
database. I showed the code to do that using the GZipStream object which
is part of System.IO.Compression namespace. I hope the code will help you
when you’ll ever need to compress data.