Note - this answer suggests an alternative to SharpZipLib
DotNetZip has a string indexer on the ZipFile class to make this really easy.
using (ZipFile zip = ZipFile.Read(sourcePath)
{
zip["NameOfFileToUnzip.txt"].Extract();
}
You don't need to fiddle with inputstreams and outputstreams and so on, just to extract a file. On the other hand if you want the stream, you can get it:
using (ZipFile zip = ZipFile.Read(sourcePath)
{
Stream s = zip["NameOfFileToUnzip.txt"].OpenReader();
// fiddle with stream here
}
You can also do wildcard extractions.
using (ZipFile zip = ZipFile.Read(sourcePath)
{
// extract all XML files in the archive
zip.ExtractSelectedEntries("*.xml");
}
There are overloads to specify overwrite/no-overwrite, different target directories, etc. You can also extract based on criteria other than the filename. For example, extract all files newer than January 15, 2009:
// extract all files modified after 15 Jan 2009
zip.ExtractSelectedEntries("mtime > 2009-01-15");
And you can combine criteria:
// extract all files that are modified after 15 Jan 2009) AND larger than 1mb
zip.ExtractSelectedEntries("mtime > 2009-01-15 and size > 1mb");
// extract all XML files that are modified after 15 Jan 2009) AND larger than 1mb
zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15 and size > 1mb");
You don't have to extract the files that you select. You can just select them and then make decisions on whether to extract or not.
using (ZipFile zip1 = ZipFile.Read(ZipFileName))
{
var PhotoShopFiles = zip1.SelectEntries("*.psd");
// the selection is just an ICollection<ZipEntry>
foreach (ZipEntry e in PhotoShopFiles)
{
// examine metadata here, make decision on extraction
e.Extract();
}
}