Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Directory.GetDirectories excluding folders

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",
                                                       "LocalService",
                                                       "Public",
                                                       "Administrator",
                                                       "Default User",
                                                       "NetworkService"
                                                   };

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?

like image 626
Clu Avatar asked Feb 20 '23 22:02

Clu


1 Answers

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>
{
    Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
    // etc.
}
like image 84
Eric J. Avatar answered Mar 04 '23 09:03

Eric J.