Reputation: 95
I would like to select all documents which have exact 4 "unknown" characters at the place where the asterisk is: (for example "****" could be "2018")
foreach (string s in Directory.GetFiles(@"C:\Users\MyUser\Documents\ExampleTitle ****.xml").Select(Path.GetFileName))
{
// Do something!
}
I know the asterisk * will match every character, no matter how many characters are between the asterisk. But as described, I want to select only results with a specific amount of unknown characters.
Upvotes: 2
Views: 946
Reputation: 627468
You cannot specify wildcards in the path argument, you need to provide the path and a search pattern, see GetFiles(String, String)
.
The search pattern accepts two wildcards, ?
for a single char and *
for any amount of chars. Hence, you need
Directory.GetFiles(@"C:\Users\MyUser\Documents", "ExampleTitle ????.xml")
If you plan to match only digits there you will have to use a regex to filter the results of Directory.GetFiles
:
var fileList = Directory.GetFiles(@"C:\Users\MyUser\Documents", "*.xml")
.Where(p => Regex.IsMatch(Path.GetFileName(p), @"^ExampleTitle [0-9]{4}\.xml$"))
.ToList();
Here, Directory.GetFiles(@"C:\Users\MyUser\Documents", "*.xml")
will fetch all XML files in the given folder, and those that entirely match the ExampleTitle <4-DIGITS>.xml
pattern will be returned then with the Where
clause.
Upvotes: 3