我想返回'SomeFolder'目录中所有子目录的列表不包括'Admin'和'Templates'目录。
我有以下文件夹结构(简化):
C:\inetpub\wwwroot\MyWebsite\SomeFolder\RandomString
C:\inetpub\wwwroot\MyWebsite\SomeFolder\RandomString
C:\inetpub\wwwroot\MyWebsite\SomeFolder\RandomString
C:\inetpub\wwwroot\MyWebsite\SomeFolder\Admin
C:\inetpub\wwwroot\MyWebsite\SomeFolder\Templates
'SomeFolder'可以包含不同数量的'RandomString'文件夹(大约从10到100)。
以下是我的尝试:
var dirs = Directory.GetDirectories(Server.MapPath(".."))
.Where(s => !s.EndsWith("Admin") || !s.EndsWith("Templates"));
foreach (string dir in dirs)
{
lit.Text += Environment.NewLine + dir;
}
这将返回完整的文件夹列表(如上所示),而不会过滤掉“管理员”和“模板”。
有趣的是,如果我将LINQ .Where
子句更改为 include ,而不是 exclude ,'Admin'和'Templates',它会起作用,这意味着它返回只是“管理员”和“模板”的路径。
.Where(s => s.EndsWith("Admin") || s.EndsWith("Templates"));
如果LINQ不是解决方案,有没有办法使用GetDirectories SearchPattern过滤目录?
答案 0 :(得分:8)
与(A || B)相反的是(!A&&!B),所以在你的代码中它应该是&&,而不是|| ......
答案 1 :(得分:6)
您可以执行以下操作:
//list your excluded dirs
private List<string> _excludedDirectories= new List<string>() { "Admin", "Templates" };
//method to check
static bool isExcluded(List<string> exludedDirList, string target)
{
return exludedDirList.Any(d => new DirectoryInfo(target).Name.Equals(d));
}
//then use this
var filteredDirs = Directory.GetDirectories(path).Where(d => !isExcluded(_excludedDirectories, d));