Dan Byström’s Bwain

Blog without an interesting name

Archive for March, 2007

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() )
        {

            case
"upgrade.bin":
                abyteUpgrader =
new byte[zis.Length];
                zis.Read( abyteUpgrader, 0, (
int)zis.Length );
                break;
            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;
                break;
        }

Posted in Programming | Leave a Comment »