我正在尝试使用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吗?有没有人知道我能不能不用手把整个拉链拉开就能做到?
发布于 2008-11-30 02:24:17
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
}
}发布于 2008-11-30 02:29:32
FastZip.ExtractZip (string zipFileName, string targetDirectory, string fileFilter)可以提取一个或多个基于文件过滤器(即正则表达式字符串)的文件
下面是关于文件过滤器的文档:
// A filter is a sequence of independant <see cref="Regex">regular expressions</see> 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.
// </summary>
// <example>The following expression includes all name ending in '.dat' with the exception of 'dummy.dat'
// "+\.dat$;-^dummy\.dat$"因此,对于名为myfile.dat的文件,您可以使用"+.*myfile.dat$“作为文件筛选器。
发布于 2009-02-12 22:47:52
注意-此答案建议使用SharpZipLib的替代方案
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 ICollection<ZipEntry>
foreach (ZipEntry e in PhotoShopFiles)
{
// examine metadata here, make decision on extraction
e.Extract();
}
}https://stackoverflow.com/questions/328343
复制相似问题