C#: Get the 5 newest (last modified) files from a directory

Here's a general way to do this with LINQ:

 Directory.GetFiles(path)
             .Select(x => new FileInfo(x))
             .OrderByDescending(x => x.LastWriteTime)
             .Take(5)
             .ToArray()

I suspect this isn't quite what you want, since your code examples seem to be working at different tasks, but in the general case, this would do what the title of your question requests.


While the answer Paul Phillips provided worked. It's worth to keep in mind that the FileInfo.LastWriteTime & FileInfo.LastAccessTime do not always work. It depends on how the OS is configured or could be a caching issue.

.NET FileInfo.LastWriteTime & FileInfo.LastAccessTime are wrong

File.GetLastWriteTime seems to be returning 'out of date' value


It sounds like you want a string array of the full filepaths of all the files in a directory.

Given you already have your FileInfo enumerable, you can do this:

var filenames = files.Select(f => f.FullName).ToArray();

If you wanted just the filenames, replace FullName with Name.