Sorting the result of Directory.GetFiles in C#

prosseek picture prosseek · Jun 9, 2011 · Viewed 90.5k times · Source

I have this code to list all the files in a directory.

class GetTypesProfiler
{
    static List<Data> Test()
    {
        List<Data> dataList = new List<Data>();
        string folder = @"DIRECTORY";
        Console.Write("------------------------------------------\n");
        var files = Directory.GetFiles(folder, "*.dll");
        Stopwatch sw;
        foreach (var file in files)
        {   
            string fileName = Path.GetFileName(file);
            var fileinfo = new FileInfo(file);
            long fileSize = fileinfo.Length;
            Console.WriteLine("{0}/{1}", fileName, fileSize);
        }
        return dataList;
    }
    static void Main()
    {
         ...
    }
}

I need to print out the file info based on file size or alphabetical order. How can I sort the result from Directory.GetFiles()?

Answer

Jon picture Jon · Jun 9, 2011

Very easy with LINQ.

To sort by name,

var sorted = Directory.GetFiles(".").OrderBy(f => f);

To sort by size,

var sorted = Directory.GetFiles(".").OrderBy(f => new FileInfo(f).Length);