Reputation: 270
I am writing a code to get the sub directories from the output folder with names "1", "2", "3", "4" etc. (i.e. sub directory with only number names)
For example: This is my output folder:C:\Users\xyz\Desktop\Output
I want to get sub directories with names
"1", "2", "3", "4"
Output:
C:\Users\xyz\Desktop\Output\A\A1\1
C:\Users\xyz\Desktop\Output\A\A1\2
C:\Users\xyz\Desktop\Output\A\A1\3
C:\Users\xyz\Desktop\Output\A\A1\4
C:\Users\xyz\Desktop\Output\A\A2\1
C:\Users\xyz\Desktop\Output\A\A2\2
In my code I tried to use the search pattern but was not able to find the desired output:
Here is the snippet, which gets all the sub directories with name "1"
string[] destDir1 = Directory.GetDirectories(
destinationFolderPath,
"1",
SearchOption.AllDirectories);
So in order to get all the directories with names "1", "2", "3" and "4" I used the square bracket wild card as below and this does not work.
string[] destDir1 = Directory.GetDirectories(
destinationFolderPath,
"[0-9]",
SearchOption.AllDirectories);
I followed the msdn link to get more options for search pattern wildcards
What is wrong in this logic?
Upvotes: 1
Views: 2605
Reputation: 8025
With Regex, you can do like this:
List<string> destDir1 = Directory.GetDirectories(folderPath, "*",
SearchOption.AllDirectories)
.Where(f => Regex.IsMatch(f, @"[\\/]\d+$")).ToList();
[\/]\d+$
match a folder have / or \ ([\\/]
) follow by one or more (+
) digit (\d
) at the end ($
).
Above code return a List<string>
, each string have last part is a number, i.e: D:\folder\1234
, but don't match D:\folder\aaa111
D:\1\folder
, use following code:
List<string> destDir1 = Directory.GetDirectories(folderPath, "*",
SearchOption.AllDirectories)
.Where(f => Regex.IsMatch(f, @"[\\/]\d+[\\/$]")).ToList();
It will match folders like D:\1234\child
, D:\child\1234
, but don't match D:\aaa111\child
Upvotes: 2
Reputation: 6538
you should do something like this (because GetDirectories does not support regex) :
DirectoryInfo dInfo = new DirectoryInfo(@"C:\Test");
var allDirs = dInfo.GetDirectories();
var matchingDirs = allDirs.Where(info => Regex.Match(info.Name, "[0-9]", RegexOptions.Compiled).Success);
Upvotes: 1
Reputation: 43876
The msdn link you posted is for search patterns in Visual Studio (the ones you use when you search in your code files).
There is no support for (regex) search patterns or wildcards other than (normal DOS) *
and ?
in GetDirectories
.
So you will probably have to enumerate all directories and check their names in code.
From the MDSN about GetDirectories
:
searchPattern can be a combination of literal and wildcard characters, but doesn't support regular expressions. The following wildcard specifiers are permitted in searchPattern.
...
* (asterisk) Zero or more characters in that position.
? (question mark) Zero or one character in that position.
Upvotes: 0