tags:

views:

193

answers:

4

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)

+1  A: 

You can use Directory.GetLastWriteTime (or Directory.GetLastWriteTimeUtc, it doesn't really matter in this case when you're just doing relative comparisons).

Although do you just want to look at the "modified" time as reported by the OS, or do you want to find the directory with the most recently-modified file inside it? They don't always match up (that is, the OS doesn't always update the containing directory "last modified" time when it modifies a file).

Dean Harding
Most recent FOLDER (files insider are irrelevant)
Shaitan00
In that case, `Directory.GetLastWriteTime` is what you're after. Laramie's solution also works, which is pretty much as I was saying (he was just kind enough to write the code for you ;)
Dean Harding
+3  A: 

Non-recursive:

new DirectoryInfo(path).GetDirectories()
                       .OrderByDescending(d=>d.LastWriteTimeUtc).First();

Recursive:

new DirectoryInfo(path).GetDirectories("*", 
    SearchOption.AllDirectories).OrderByDescending(d=>d.LastWriteTimeUtc).First();
Matthew Flaschen
+2  A: 

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;
    }
}
Laramie
A: 

If you are building a windows service and you want to be notified when a new file or directory is created you could also use a FileSystemWatcher. Admittedly not as easy, but interesting to play with. :)

Chad Ruppert
-1 This only works if the directory is created while the application is running, which isn't necessarily true based on the information provided in the question.
Jon Seigel
That is exactly why I specified a windows service, implying it's going to be running all the time.
Chad Ruppert
That's not necessarily true. Services can be started and stopped, or run intermittently (I would argue that's a poor design, but that's a separate issue). This method would not notify the application if a folder was created before the application was *installed*, for example.
Jon Seigel