Dan Byström’s Bwain

Blog without an interesting name

Zip tip

Posted by Dan Byström on March 3, 2007

Have you ever thought “it would be a good thing if my application could store this data a ZIP file”? Either in order to save space or to bundle several files into one (or both). But then you have hesitated because you realized you’d have to go out and buy an expensive ZIP compression/uncompression library and then learn how to use it (and maybe encounter some bugs or discover some unwanted side effects or…) and so you’ve dropped the whole thing.

If so, this must mean that you haven’t found SharpZipLib yet! It really is great! And OpenSource on top of that!

Moving data in and out of a ZIP file is a breeze, and it works completely with streams so you can, for example, work with MemoryStreams if you don’t want to work with disk based files. Highly recommended!

Some sample code that scans a ZIP file for two particular files and processes some data:

using ( FileStream fs =new FileStream( strZipFile,FileMode.Open,FileAccess.Read ) )
using ( ZipInputStream zis = new ZipInputStream( fs ) )
while ( (theEntry = zis.GetNextEntry()) != null )
switch ( theEntry.Name.ToLower() )

                abyteUpgrader =
new byte[zis.Length];
                zis.Read( abyteUpgrader, 0, (
int)zis.Length );
            case "upgrade.txt":
                byte[] ab = new byte[zis.Length];
                zis.Read( ab, 0, (
int)zis.Length );
                string s = Encoding.Default.GetString( ab );
                if ( Regex.IsMatch( s, @"\d{4}-\d{2}-\d{2}" ) )
                    fFoundNewVersion = s.CompareTo( strMinimumDate ) > 0;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: