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()?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With