C # Directory.GetDirectories excluding folders
I am trying to iterate through the list of custom folders in windows in the "c: \ Users" folder, but exclude the built-in Microsoft custom folders, below is the segment of code I am using to accomplish this feat, but it doesn't work as expected for some reason ...
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 am not sure why this is not working, can someone explain it to me?
source to share
Directory.GetDirectories () returns the full path to the directory, not just the last part of the directory.
As long as you remove the last component of the path returned by GetDirectories () and compare it to what is currently in your array, it will lead to false positives and false negatives.
Use Environment.SpecialFolders instead to get the path to a given special folder specific to the current version of the user and operating system.
private readonly List<String> _exclusion = new List<String>
{
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
// etc.
}
source to share