Using method syntax might make this read a bit easier along with a Where()
clause to specify what you are searching for:
// You must specify the path you want to search ({your-path}) when using the GetFiles()
// method.
var mostRecentFile = logDirectory.GetFiles("{your-path}")
.Where(f => f.Name.StartsWith("Receive"))
.OrderByDescending(f => f.LastWriteTime)
.FirstOrDefault();
Likewise, you can specify a search pattern within the Directory.GetFiles()
method as a second parameter :
// You can supply a path to search and a search string that includes wildcards
// to search for files within the specified directory
var mostRecentFile = logDirectory.GetFiles("{your-path}","Receive*")
.OrderByDescending(f => f.LastWriteTime)
.FirstOrDefault();
It's important to remember that FirstOrDefault()
will return the first element that is found or null
if no items are found, so you'll need to perform a check to ensure that you found something before continuing :
// Get your most recent file
var mostRecentFile = DoTheThingAbove();
if(mostRecentFile != null)
{
// A file was found, do your thing.
}