Sorting the results of DirectoryInfo.GetFiles
Say you wanted toget a list of all the SLN (Visual Studio Solution) files in a given directory and all child directories, sorted alphabetically, you could use something similar to this:
public static void GetSolutionList()
{
DirectoryInfo d = new DirectoryInfo(@"C:\Solutions\");
FileInfo[] items = d.GetFiles("*.sln", SearchOption.AllDirectories);
Array.Sort(items, new FileInfoComparer());
List<string> solutions = new List<string>(); foreach (FileInfo f in items)
{
solutions.Add(f.FullName);
}
}
public class FileInfoComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return ((new CaseInsensitiveComparer()).Compare(y.Name, x.Name));
}
}
The key bit of "magic" is the FileInfoComparer - whilst this is a simple one, it shows how easy it is to implement a comparer for the purposes of sorting!