Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose the last modified file from the directory? [duplicate]

Tags:

c#

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?

like image 856
HotTeaLover Avatar asked Dec 05 '25 07:12

HotTeaLover


2 Answers

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.

like image 152
Jon Avatar answered Dec 08 '25 12:12

Jon


var file = new DirectoryInfo(dirname)
                .GetFiles()
                .OrderByDescending(f => f.LastWriteTime)
                .FirstOrDefault();
like image 37
I4V Avatar answered Dec 08 '25 13:12

I4V