Home > Uncategorized > Using System.IO.Packaging to Read & Write Zip Archives

Using System.IO.Packaging to Read & Write Zip Archives

While building a content packaging system for one of my recent applications, I found the need to write to and read from Zip archive files and came across the DotNetZip project on CodePlex. This project looks great, but I don’t want my applications referencing any 3rd party dll files and I’m hesitant to use anything released under any kind of license, GPL or not.

I found a working example of writing to Zip archives using System.IO.Packaging on Jon Galloway’s Blog.

This code works great for writing to Zip files, but what about extracting files?

Microsoft provides the “Reading a Package Sample” code sample which extracts resources based on file relationships.

The code sample uses two foreach loops to look at PackageRelationships and then extract necessary files.

If we don’t care about these relationships and just want to extract the files, all we have to do is loop through the PackageParts:

using (Package package =
 Package.Open(targetFilename, FileMode.Open, FileAccess.Read))
{
  foreach (PackagePart pp in package.GetParts())
  {
    ExtractPart(pp, targetFilename);
  }
}

That’s it!

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: