views:

207

answers:

4

I have a network folder which can contain up to 10,000 files (usually around 5000).

What is the fatest way I can get the filepath of the most recently created file in that folder using c#?

Currently I am using the below, but wondered if there was a quicker way.

Thanks.

DirectoryInfo di = new DirectoryInfo(xmlFileLocation);
var feedFiles = di.GetFiles("*.xml");
var sortedFeedFile = from s in feedFiles
                     orderby s.CreationTime descending
                     select s;

if(sortedFeedFile.Count() > 0){
    mostRecentFile = sortedFeedFile.First();
}
A: 

This might help... http://www.4guysfromrolla.com/articles/060403-1.2.aspx

Jason
+5  A: 

Sorting the files is taking you O(nlogn) time. If all you need is the most recently created, it would be faster to just scan through the files and find the most recent---O(n).

Keith Smith
I very much doubt the sorting time is that relevant, however it is certainly something to look at under a profiler.
RichardOD
+1  A: 

I reckon your best chance is to consider creating a Win32 API call- this may or may not be faster, but it might be worth investigating. See WIN32_FILE_ATTRIBUTE_DATA Structure to do this.

RichardOD
A: 

This gets the FileInfo, or null if there are no files, without sorting:

var feedFiles = di.GetFiles("*.xml");
FileInfo mostRecentFile = null;
if (feedFiles.Any())
{
    mostRecentFile = feedFiles
        .Aggregate((x, c) => x.CreationTime > c.CreationTime ? x : c);
}
Handcraftsman
Interesting technique to bypass sorting- hadn't thought of that. Personally though I don't think the sorting is a performance issue.
RichardOD