Sorting the results of DirectoryInfo.GetFiles

| | Comments (0)
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!

Leave a comment

About this Entry

This page contains a single entry by Rob published on May 22, 2009 8:30 AM.

A number that equals twice the sum of its decimal digits was the previous entry in this blog.

Miscellanea 16 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.02