How to find the most recent file in a directory using .NET, and without looping?
Expanding on the first one above, if you want to search for a certain pattern you may use the following code:
using System.IO;
using System.Linq;
...
string pattern = "*.txt";
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();
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();
If you want to search recursively, you can use this beautiful piece of code:
public static FileInfo GetNewestFile(DirectoryInfo directory) {
return directory.GetFiles()
.Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
.OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
.FirstOrDefault();
}
Just call it the following way:
FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"C:\directory\"));
and that's it. Returns a FileInfo
instance or null
if the directory is empty.