As most of you know, my day job is developing software. So every once in a while I'll be posting about some interesting things that I run into when programming... and here's one of them.
One of my applications grabs a list of a large number of files (sometimes 300+), and most of the time I'm looking for files that were created within the past 3 days. I've been using the standard DirectoryInfo.GetFiles() method, but the problem I ran into was that it sorts the array by file name and not by creation date. To sort it by creation date, I had to create my own class that implements the IComparer interface. This gave me the functionality to sort by whatever I wanted (in my case, I needed creation date).
internal class CustomCompare : IComparer<FileInfo> {
public int Compare(FileInfo x, FileInfo y) {
return DateTime.Compare(
x.CreationTime, y.CreationTime);
}
}
Note: By using the generic IComparer interface, I was able to save from doing unnecessary casting from the object type to the FileInfo type.
Now to use this new class, I just need to call the Array.Sort() method and use the custom class:
// Builds an array of all the files
DirectoryInfo di = new DirectoryInfo(@"C:\Directory");
FileInfo[] fi = di.GetFiles();
// Sorts the FileInfo[] array
Array.Sort(fi, new CustomCompare());
It's as easy as that! Now I have a list of files that are sorted by creation date instead of by file name.