How to find the most recent file in a directory using .NET, and without looping?
I need to find the most recently modified file in a directory.
I know I can loop through every file in a folder and compare File.GetLastWriteTime
, but is there a better way to do this without looping?.
how about something like this...
var directory = new DirectoryInfo("C:\\MyDirectory");
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
// or...
var myFile = directory.GetFiles()
.OrderByDescending(f => f.LastWriteTime)
.First();
Expanding on the first one above, if you want to search for a certain pattern you may use the following code:
string pattern = "*.txt";
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();