Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a file based on string

Tags:

c#

file

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?

like image 790
user726720 Avatar asked May 16 '26 12:05

user726720


1 Answers

FileInfo latestByWriteTime = new DirectoryInfo( @"C:\" )
    .GetFiles()
    .Where( f => f.Name.Contains( "221218", StringComparer.OrdinalIgnoreCase ) )
    .OrderByDescending( f => f.LastWriteTime )
    .FirstOrDefault();
like image 53
Dai Avatar answered May 19 '26 02:05

Dai