我正在尝试使用SharpZipLib从zip存档中提取指定的文件.我见过的所有例子总是希望你能解压缩整个拉链,并按照以下方式做一些事情:
FileStream fileStreamIn = new FileStream (sourcePath, FileMode.Open, FileAccess.Read); ZipInputStream zipInStream = new ZipInputStream(fileStreamIn); ZipEntry entry; while (entry = zipInStream.GetNextEntry() != null) { // Unzip file }
我想做的是:
ZipEntry entry = zipInStream.SeekToFile("FileName");
因为我的需求涉及使用zip作为包,只根据需要将文件抓取到内存中.
有人熟悉SharpZipLib吗?有没有人知道我是否可以手动完成整个拉链?
ZipFile.GetEntry应该做的伎俩:
using (var fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read)) using (var zf = new ZipFile(fs)) { var ze = zf.GetEntry(fileName); if (ze == null) { throw new ArgumentException(fileName, "not found in Zip"); } using (var s = zf.GetInputStream(ze)) { // do something with ZipInputStream } }
FastZip.ExtractZip (string zipFileName, string targetDirectory, string fileFilter)
可以根据文件过滤器提取一个或多个文件(即常规expressoin字符串)
这是关于文件过滤器的文档:
// A filter is a sequence of independantregular expressions separated by semi-colons ';' // Each expression can be prefixed by a plus '+' sign or a minus '-' sign to denote the expression // is intended to include or exclude names. If neither a plus or minus sign is found include is the default // A given name is tested for inclusion before checking exclusions. Only names matching an include spec // and not matching an exclude spec are deemed to match the filter. // An empty filter matches any name. // //The following expression includes all name ending in '.dat' with the exception of 'dummy.dat' // "+\.dat$;-^dummy\.dat$"
因此,对于名为myfile.dat的文件,您可以使用"+.*myfile\.dat $"作为文件过滤器.
DotNetZip在ZipFile类上有一个字符串索引器,使这很容易.
using (ZipFile zip = ZipFile.Read(sourcePath) { zip["NameOfFileToUnzip.txt"].Extract(); }
您不需要调整输入流和输出流等,只需提取文件即可.另一方面,如果你想要流,你可以得到它:
using (ZipFile zip = ZipFile.Read(sourcePath) { Stream s = zip["NameOfFileToUnzip.txt"].OpenReader(); // fiddle with stream here }
您也可以进行通配符提取.
using (ZipFile zip = ZipFile.Read(sourcePath) { // extract all XML files in the archive zip.ExtractSelectedEntries("*.xml"); }
有重载指定覆盖/不覆盖,不同的目标目录等.您还可以根据文件名以外的条件进行提取.例如,提取比2009年1月15日更新的所有文件:
// extract all files modified after 15 Jan 2009 zip.ExtractSelectedEntries("mtime > 2009-01-15");
你可以结合标准:
// 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");
您不必解压缩所选的文件.您可以选择它们,然后决定是否提取.
using (ZipFile zip1 = ZipFile.Read(ZipFileName)) { var PhotoShopFiles = zip1.SelectEntries("*.psd"); // the selection is just an ICollectionforeach (ZipEntry e in PhotoShopFiles) { // examine metadata here, make decision on extraction e.Extract(); } }