Enumerating files in dir sorted by time

  • Thread starter Thread starter Dan
  • Start date Start date
D

Dan

In .NET, what's the most efficient way to enumerate through all the files in
a directory sorted by time (from oldest to newest)?
 
Here's what I ended up doing. First I build an IComparer class to compare
the LastWriteTime of each FileSystemInfo object in an array. Then I sorted
all the FileSystemInfo objects returned by DirectoryInfo.GetFileSystemInfos.

public class ReverseDateSorter : IComparer
{

// Calls CaseInsensitiveComparer.Compare with the parameters
reversed.
int IComparer.Compare( Object x, Object y )
{
return DateTime.Compare(((FileSystemInfo)x).LastWriteTime,
((FileSystemInfo)y).LastWriteTime);
}
}


ReverseDateSorter dateSorter = new ReverseDateSorter();
System.IO.DirectoryInfo dir = new DirectoryInfo(@"c:\junk");
FileSystemInfo[] files = dir.GetFileSystemInfos(@"*.*");
Array.Sort(files, dateSorter);
 
Back
Top