c# Directory.GetDirectories excluding folders

Go To StackoverFlow.com


I'm trying to iterate through a list of users folders in windows in "c:\Users" but exclude the microsoft built-in user folders, the below is the code segment I'm using to accomplish this feat but it's for some reason not working as intended.

private readonly List<String> _exclusion = new List<String>
                                                       "All Users",
                                                       "Default User",

public static bool FoundInArray(List<string> arr, string target)
    return arr.Exists(p => p.Trim() == target);

foreach (string d in Directory.GetDirectories(sDir).Where(d => !FoundInArray(_exclusion,d)))
    richTextBox1.Text += d + Environment.Newline;

I'm not sure why this isn't working, can anyone provide some insight on this for me?

2012-04-04 00:39
by Clu
Use debugger and place a breakpoint. Then Iterate over the source looking at your variables. Tell us which part doesn't work as intended and what result do you get instead - surfen 2012-04-04 00:43


In your lambda expression: 'd' is the full name of the directory (with the path), and therefore is not actually in the array.

You could do:

public static bool FoundInArray(List<string> arr, string target)
    return arr.Any(p => new DirectoryInfo(target).Name == p);
2012-04-04 00:45
by SimpleVar
Do you know how I'd return the DirectoryInfo d.Name from that - Clu 2012-04-04 00:46
new DirectoryInfo(d).Nam - SimpleVar 2012-04-04 00:47
Checking for a "contains" match on the string will yield false results under certain edge cases - Eric J. 2012-04-04 00:51
@EricJ. Elaborate - SimpleVar 2012-04-04 00:51
Just one example: C:\Users\EricJ\DefaultXYZ is also removed by the Contains check - Eric J. 2012-04-04 00:58
Oh I see, thanks for pointing that out. Well it's the safest to go with directory info name. Edited - SimpleVar 2012-04-04 01:00


Directory.GetDirectories() returns the full path of the directory, not just the last part of the directory.

While you COULD strip off the last component of the path returned by GetDirectories() and compare that to what's currently in your array, that will result in false positives and false negatives.

Instead, use Environment.SpecialFolders to get the path for a given special folder specific to the current user and operating system version.

private readonly List<String> _exclusion = new List<String>
    // etc.
2012-04-04 00:46
by Eric J.