views:

2800

answers:

3

I need to find the most recently modified file in a directory. I know I can loop through every file in a folder and compare File.GetLastWriteTime but is there a better way to do this without looping?

A: 

You can react to new file activity with FileSystemWatcher.

scottmarlowe
It doesn't work because a file can be modified while his application is not running.
Francis B.
he didn't give that kind of detail... How do we know it isn't a persistant app?
scottmarlowe
We don't, but Scott has a better solution what works in both cases.
Badaro
+9  A: 

how about something like this...

var directory = new DirectoryInfo("C:\\MyDirectory");
var myFile = (from f in directory.GetFiles()
             orderby f.LastWriteTime descending
             select f).First();

// or...
var myFile = directory.GetFiles()
             .OrderByDescending(f => f.LastWriteTime)
             .First();
Scott Ivey
Personally, I find that the non-sugared version is easier to read: `directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First()`
Jørn Schou-Rode
yeah, i agree most of the time too - but when giving examples the query syntax makes it a bit more obvious that it's a linq query. I'll update the example with both options to clarify.
Scott Ivey
Thanks! Now I just need to convince my boss to expedite the process of upgrading us from .net 2.0 so I can use Linq :)
Chris Klepeis
you can use linq with 2.0 SP1 with a little extra work - just reference the System.Core.dll file from 3.5, and set it to "copy local"
Scott Ivey
A: 

A non-LINQ version:

private FileInfo GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)
{
    FileInfo[] files = directoryInfo.GetFiles();

    FileInfo[] lastUpdatedFile = null;
    DateTime lastUpdate = new DateTime(1, 0, 0);

    foreach (FileInfo file in files)
    {
        if (file.LastAccessTime > lastUpdate)
        {
            lastUpdatedFile = file;
            lastUpdate = file.LastAccessTime;
        }
    }

    return lastUpdatedFile;           
}
TimothyP
Sorry , didn't see the fact that you did not want to loop.Anyway... perhaps it will help someone searching something similar
TimothyP
This code does not compile. - lastUpdatedFile should not be an array. - The initial value for lastUpdate is invalid (0001/0/0).
Lars A. Brekken