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?
It doesn't work because a file can be modified while his application is not running.
Francis B.
2009-07-24 20:27:54
he didn't give that kind of detail... How do we know it isn't a persistant app?
scottmarlowe
2009-07-24 20:46:34
We don't, but Scott has a better solution what works in both cases.
Badaro
2009-07-24 21:12:15
+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
2009-07-24 20:25:44
Personally, I find that the non-sugared version is easier to read: `directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First()`
Jørn Schou-Rode
2009-07-24 20:32:09
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
2009-07-24 20:48:22
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
2009-07-24 20:54:28
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
2009-07-24 21:19:38
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
2009-11-23 07:51:11
Sorry , didn't see the fact that you did not want to loop.Anyway... perhaps it will help someone searching something similar
TimothyP
2009-11-23 07:52:33
This code does not compile. - lastUpdatedFile should not be an array. - The initial value for lastUpdate is invalid (0001/0/0).
Lars A. Brekken
2010-05-13 21:38:39