SmartZip Archive File Library – Creating and Using Archive Files - Opening a Zip File
(Page 3 of 4 )
Above, I presented the process required to write a zip archive to a file. Obviously, you might also want to open a zip file and manipulate its contents programmatically in some way. There are a couple of ways to do this. If you plan on actually extracting the file data, it is generally best to use the ZipInputStream class, as this allows you to step sequentially through a zip archive and extract each entry’s contents. If all you need to do is list the names and maybe some other metadata about each entry, the ZipFile class is best. If you want to actually extract data from a ZipFile class, you must get a stream from the ZipFile class for each entry you want to extract.
First, I will address using the ZipFile class. You can create a Zip file by giving it either a FileStream, a regular Stream, or a string containing a file name. After opening the file into a ZipFile object, you can walk through the ZipEntry objects to get information on each individual file and get streams to uncompress each individual file. The code to do this looks like the following:
Steam outFile = new Stream();
ZipFile zip = new ZipFile(“test.zip”);
foreach(ZipEntry file in zip)
{
outFile = zip.GetInputStream(file);
}
You can then take that stream and use it to write out to a file or do something else interesting with it. You can also not even get the input stream at all and simply just get the metadata for each entry.
The other way to access a zip file is to open it into a ZipInputStream. This is simpler to walk through and extract each file. This method extracts each entry into a byte array. You can then take that byte array and pipe it into a file stream to write the file out to the hard drive.
ZipInputStream zip = new ZipInputStream(File.OpenRead(“test.zip”));
ZipEntry entry;
while(entry = zip.GetNextEntry()))
{
byte[] data = new byte[2048];
zip.read(data,0,data.length);
FileStream fs = File.Create(entry.Name);
fs.write(data,0,data.length);
fs.close();
}
zip.close();
The above code will open the zip file and read each entry and write the first 2048 bytes out to a file named correctly.
Next: Other Formats >>
More .NET Articles
More By Michael Swanson