4

如何删除 .zip 中的目录及其中的所有文件(最好使用 DotNetZip)?

现在我正在浏览 zip 中的所有文件,但它不起作用:

foreach (ZipEntry e in zip)
{
    //If the file is in the directory I want to delete
    if(e.FileName.Substring(0, 9) == "FolderName/")
    {
        zip.RemoveEntry(e.FileName);                          
    }
}

有没有更好的方法,如果没有,我将如何进行这项工作?

4

4 回答 4

9

这是一个简单的方法:

using (ZipFile zip = ZipFile.Read(@"C:\path\to\MyZipFile.zip"))
{
    zip.RemoveSelectedEntries("foldername/*"); // Delete folder and its contents
    zip.Save();
}

Documentation here http://dotnetzip.herobo.com/DNZHelp/Index.html

于 2014-09-04T05:27:37.720 回答
7

第一强。从集合中删除元素时不要使用 foreach 循环。
我会尝试这种方式

for(int x = zip.Count -1; x >= 0; x--) 
{ 
    ZipEntry e = zip[x];
    if(e.FileName.Substring(0, 9) == "FolderName/") 
        zip.RemoveEntry(e.FileName);                           
} 

但是,查看 ZipFile 类的方法时,我注意到方法:返回 ICollection 的 SelectEntries。所以我认为可以这样做:
编辑:使用重载版本 SelectEntries(string,string)

var selection = zip1.SelectEntries("*.*", "FolderName");
for(x = selection.Count - 1; x >= 0; x--)
{
    ZipEntry e = selection[x];
    zip.RemoveEntry(e.FileName);                           
}

删除 zipfile 中所有条目的循环

于 2012-03-24T20:17:13.360 回答
2

You can achieve it as follows

using (ZipArchive zip = ZipFile.Open(@"C:\path\to\MyZipFile.zip", ZipArchiveMode.Update))
{
    zip.Entries.Where(x => x.FullName.Contains("Foldername")).ToList()
        .ForEach(y =>
        {
            zip.GetEntry(y.FullName).Delete();
        });
}

Note : If all the files from the folder is deleted then the folder will be automatically removed.

于 2020-03-06T12:31:52.240 回答
0

In order to delete the directory and all nested child entries, I used

var sel = (from x in zip.Entries where x.FileName.StartsWith(path, StringComparison.OrdinalIgnoreCase) select x.FileName).ToList();
foreach (var fn in sel)
{
     zip.RemoveEntry(fn);
}

Note that the path must end with a slash, like dir/subdir/

于 2016-06-12T17:21:47.443 回答