使用Directory.GetDirectories时如何排除文件夹 [英] How to exclude folders when using Directory.GetDirectories

查看:369
本文介绍了使用Directory.GetDirectories时如何排除文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回"SomeFolder"目录中的所有子目录的列表,不包括"Admin"和"Templates"目录.

I want to return a list of all the subdirectories in the 'SomeFolder' directory excluding the 'Admin' and 'Templates' directories.

我具有以下文件夹结构(简化了):

I have the following folder structure (simplified):

    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).

'SomeFolder' can contain a varying number a 'RandomString' folders (anywhere from ~10 to ~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;
    }

这将返回未过滤出管理员"和模板"的文件夹的完整列表(如上所示).

This returns the full list of folders (shown above) without 'Admin' and 'Templates' filtered out.

有趣的是,如果我将LINQ .Where子句更改为 include ,而不是 exclude ,"Admin"和"Templates",则它起作用,这意味着它只返回管理员"和模板"的路径.

Interestingly, if I change the LINQ .Where clause to include, instead of exclude, 'Admin' and 'Templates' it works, meaning it returns just the paths for 'Admin' and 'Templates'.

.Where(s => s.EndsWith("Admin") || s.EndsWith("Templates"));

如果LINQ不是解决方案,是否可以使用GetDirectories SearchPattern筛选出目录?

If LINQ is not the solution, is there any way to use the GetDirectories SearchPattern to filter out directories?

推荐答案

(A || B)的对立面是(!A&&!B),因此在您的代码中,它应该是&& ;,不是|| ...

the opposite of (A || B) is (!A && !B), so in your code it should be &&, not ||...

这篇关于使用Directory.GetDirectories时如何排除文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆