Bob
Bob

Reputation: 191

Exclude directories from file search in C#

I try to search a file system using

Directory.EnumerateDirectories

Let's say i want to search the whole C:\ in Windows, but i want to exclude some pathes (e.g. C:\asdf, C:\lorem\ipsum) or folder names (e.g. folder1, folder2, ...). I want to create a statement that filters out pathes and folders from a string list. That means:

List<string> exclude = new List<string>{@"C:\asdf", @"C:\lorem\ipsum", "folder2"};

How can i exclude these pathes and folder names from the above directory search?

Upvotes: 0

Views: 508

Answers (1)

Woldemar89
Woldemar89

Reputation: 672

List<string> exclude = new List<string> { @"C:\asdf", @"C:\lorem\ipsum", "folder2" };

Func<string, string, bool> containsCaseInsensitivePredicate = (s, p) => s.IndexOf(p, StringComparison.OrdinalIgnoreCase) != -1;

Func<string, bool> notInExcludeListPredicate = (s) => !exclude.Any(ex => containsCaseInsensitivePredicate(ex, s));

IEnumerable<string> directories = Directory.EnumerateDirectories(@"C:\").Where(notInExcludeListPredicate);

Upvotes: 3

Related Questions