简体   繁体   中英

Get most recent modification date of all the files in a directory

I am a real newbie in C#, and I am trying to get the most recent modification time (LastWriteTime) for any file in a directory.

What is a simple way to get this information?

I would simplify your code to use this approach:

DirectoryInfo di_source_directory = new DirectoryInfo(@"C:\MyFolder");
FileSystemInfo[] ls_fi = di_source_directory.GetFileSystemInfos();
DateTime ts_most_recent = (ls_fi.Any() 
                 ? ls_fi.Max(fi => fi.LastWriteTime) 
                 : default(DateTime));

or just replace the default(DateTime) part with new DateTime(.....)

I could retrieve the timestamp of the most recent updated file using this code, with the help of @DiplomacyNotWar:

DirectoryInfo di_source_directory = new DirectoryInfo(@"C:\MyFolder");
FileSystemInfo[] ls_fi = di_source_directory.GetFileSystemInfos();
DateTime defaultTS = new DateTime(2022, 1, 1);
DateTime ts_most_recent = ls_fi.Select(fi => fi.LastWriteTime).DefaultIfEmpty(defaultTS).Max();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM