0

I am using Directory.GetDirectories() to get a list of folders that meet a certain criteria by using its searchPattern parameter.

I am only looking for any folders containing a specific word, say alphabet, my code is as follows:

Directory.GetDirectories(rootToSearch, "*alphabet*")

But, there is a common abbreviation that I know to expect for this word, say abc. If I was searching in Windows File Explorer I could search for *alphabet* OR *abc* and it would work as expected, however putting this as the searchPattern results in the function finding no folders, presumably because it is taking it as one search term including OR as a literal, instead of 2 terms delineated with OR.

Is there any way to achieve an OR statement in the search pattern? The MSDN says:

The search string to match against the names of subdirectories in path. This parameter can contain a combination of valid literal and wildcard characters, but it doesn't support regular expressions.

So I know that I can't use Regular Expressions. I tried using |, but that results in an Illegal characters in path error.

Tyler N
  • 301
  • 2
  • 14
  • Does this answer your question? [Can you call Directory.GetFiles() with multiple filters?](https://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters) – 41686d6564 stands w. Palestine Jan 13 '21 at 17:38
  • @41686d6564 Partially. I've answered my question to encompass how to mimic `GetDirectories()` more fully. Thank you. – Tyler N Jan 13 '21 at 18:17

1 Answers1

1

As per this question you can use LINQ to filter an array of all directories on the root, instead of using the searchPattern

But that question used GetFiles() and there are certain things to take into account when using the solution for GetDirectories()

To ensure that your search pattern is indeed being used only against the folder name rather than the entire path, use DirectoryInfo

LCase() is also used to mimic GetDirectories() accordingly.

Dim folders = Directory.GetDirectories(rootToSearch) _
    .Where(Function(s)
               Return LCase(New DirectoryInfo(s).Name).Contains("abc") Or LCase(New DirectoryInfo(s).Name).Contains("alphabet")
           End Function)
Tyler N
  • 301
  • 2
  • 14