Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the result of Directory.GetFiles in C#

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()?

like image 563
prosseek Avatar asked Jun 09 '11 14:06

prosseek


1 Answers

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); 
like image 86
Jon Avatar answered Oct 02 '22 14:10

Jon