4

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' can contain a varying number a 'RandomString' folders (anywhere from ~10 to ~100).

Here is what I have tried:

    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.

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"));

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

Dhaust
  • 5,470
  • 9
  • 54
  • 80

2 Answers2

10

You can do something like:

//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));
aiapatag
  • 3,355
  • 20
  • 24
  • 2
    wow surprisingly, when i searched this, i found [this one](http://stackoverflow.com/questions/10003440/c-sharp-directory-getdirectories-excluding-folders). very similar to mine. – aiapatag Jun 11 '13 at 04:26
  • 2
    This is a nice clean solution. I am doing a entire server. Do you think the performance will be better if I don't use DirectoryInfo and use string manipulation. IE tagert.EndWith(d) – H20rider Jul 07 '16 at 15:48
  • 1
    @H20rider, significant performance boost? no. I don't think so. – aiapatag Jul 22 '16 at 12:57
  • 3
    best answer, definitely! The chosen answer is working for this example, but this solution is clean and easy to maintain if you need to add folders / remove folders without making a huge && || && concat – Dominik Lemberger Mar 29 '17 at 14:17
9

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

Z .
  • 12,657
  • 1
  • 31
  • 56
  • 2
    Yep, that was it. Thanks. What a rookie mistake. I had even had a (obviously too quick) look at the C# operators reference to make sure I should have using the conditional and not the logical. Will accept when the 10 min window is up. – Dhaust Jun 11 '13 at 04:21