I have N files in a folder. Some information is written into them from time to time. There is no strict logic of how the information is added into them. Content of the files are not relevant.
How to get the last-modified time of every file, compare and choose the right one?
Namespace System.IO has classes that help you get information about the contents of the filesystem. Together with a little LINQ it's quite easy to do what you need:
// Get the full path of the most recently modified file
var mostRecentlyModified = Directory.GetFiles(@"c:\mydir", "*.log")
.Select(f => new FileInfo(f))
.OrderByDescending(fi => fi.LastWriteTime)
.First()
.FullName;
You do need to be a little careful here (e.g. this will throw if there are no matching files in the specified directory due to .First() being called on an empty collection), but this is the general idea.
var file = new DirectoryInfo(dirname)
.GetFiles()
.OrderByDescending(f => f.LastWriteTime)
.FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With