I have the files as follows:
Test_221218_123.txt
Test_221218_456.txt
Test_221218_789.txt
Here '221218' is the date. I have done a test as follows:
var d = new DirectoryInfo(@"C:\");
var files = d.GetFiles().Where(f => f.Name.Contains("221218"));
For testing i'm passing the date is static just for testing purposes but it will be a variable when put in production. The above is selecting all files for me. I need to select the latest file (in term's of date).
I tried as below
var files = d.GetFiles().Where(f => f.Name.Contains("221218"));
//OR
var files = d.GetFiles().Where(f => f.Name.Contains("221218")).Select(f => f.LastWriteTime);
The first one get's me a list of all the files with 221218. The second one gives me the date. How do I select the latest file?
FileInfo latestByWriteTime = new DirectoryInfo( @"C:\" )
.GetFiles()
.Where( f => f.Name.Contains( "221218", StringComparer.OrdinalIgnoreCase ) )
.OrderByDescending( f => f.LastWriteTime )
.FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With