Shaitan00
Shaitan00

Reputation: 323

How to get the newest (last modified) directory [C#]

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)

Upvotes: 32

Views: 48706

Answers (6)

Phileas Fogg
Phileas Fogg

Reputation: 161

Be warned: You might need to call Refresh() on your Directory Info object to get the correct information:

e.g. in Laramie's answer you'd edit to:

DirectoryInfo fi1 = new DirectoryInfo(subdir);
fi1.Refresh();
DateTime created = fi1.LastWriteTime;

Otherwise you might get outdated info like I did:

"Calls must be made to Refresh before attempting to get the attribute information, or the information will be outdated."

http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.refresh(v=vs.71).aspx

Upvotes: 3

Zamir
Zamir

Reputation: 401

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

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 285047

Non-recursive:

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

Recursive:

new DirectoryInfo(path).GetDirectories("*", 
    SearchOption.AllDirectories).OrderByDescending(d=>d.LastWriteTimeUtc).First();

Upvotes: 60

Chad Ruppert
Chad Ruppert

Reputation: 3680

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. :)

Upvotes: 0

Laramie
Laramie

Reputation: 5587

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;
    }
}

Upvotes: 16

Dean Harding
Dean Harding

Reputation: 72678

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).

Upvotes: 1

Related Questions