Reputation: 109
I want to get the files where the file names contains 14 digits.
foreach (var file_path in Directory.EnumerateFiles(@"F:\apinvoice", "*.pdf"))
{
}
I need to get the files only which has "14" digits.
16032021133026
17032021120457
17032021120534
Upvotes: 1
Views: 520
Reputation: 7648
Since these seem to be timestamps, another thing you could do is this;
foreach (var file_path in Directory.EnumerateFiles(@"F:\apinvoice", "*.pdf"))
{
DateTime dateTimeParsed;
var dateTimeParsedSuccesfully = DateTime.TryParseExact(file_path, "ddMMyyyyHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTimeParsed);
if(dateTimeParsedSuccesfully)
{
// Got a valid file, add it to a list or something.
}
}
Also see: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-5.0 https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-5.0
ofcourse often the timespan will often be at the end of a file, so if there are characters or something in front, you may want to pass file_path.Substring(file_path.length - 14)
to TryParseExact()
.
Upvotes: 0
Reputation: 780
I would go with regex where you specify pattern
you said you want 14 digits meaning it will ignore names like
a1603202113302
because it contains letter
therefore pattern is
^[0-9]{14}$
and full code:
Regex rx = new Regex("^[0-9]{14}$");
Directory
.EnumerateFiles(@"F:\apinvoice", "*.pdf")
.Where(x => rx.IsMatch(Path.GetFileNameWithoutExtension(x)));
Upvotes: 1
Reputation: 324
Assign it to a list
List<string> list = Directory.EnumerateFiles(@"F:\apinvoice", "*.pdf"))
List<string> whatyouwant = list.Where(l => l.Length == 14).ToList();
Upvotes: 0