Currently my application uses string[] subdirs = Directory.GetDirectories(path) to get the list of subdirectories, and now I want to extract the path to the latest (last modified) subdirectory in the list.
What is the easiest way to accomplish this? (efficiency is not a major concern - but robustness is)
Non-recursive:
new DirectoryInfo(path).GetDirectories()
.OrderByDescending(d=>d.LastWriteTimeUtc).First();
Recursive:
new DirectoryInfo(path).GetDirectories("*",
SearchOption.AllDirectories).OrderByDescending(d=>d.LastWriteTimeUtc).First();
without using LINQ
DateTime lastHigh = new DateTime(1900,1,1);
string highDir;
foreach (string subdir in Directory.GetDirectories(path)){
DirectoryInfo fi1 = new DirectoryInfo(subdir);
DateTime created = fi1.LastWriteTime;
if (created > lastHigh){
highDir = subdir;
lastHigh = created;
}
}
Try this:
string pattern = "*.txt"
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern)
orderby f.LastWriteTime descending
select f).First();
http://zamirsblog.blogspot.com/2012/07/c-find-most-recent-file-in-directory.html
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