Sort
files, sizeEach file in a directory has a size in bytes. A C# method can sort an array of these files by their sizes in bytes—from largest to smallest (or the opposite).
This logic is sometimes useful for categorization and presenting file lists. Many approaches are possible, but we use the LINQ extension methods.
We use the FileInfo
class
and its Length
property to get the length of each file. The File class
doesn't have a Length
getter, and reading in the entire file each time would be wasteful.
Directory.GetFiles
method found in the System.IO
namespace.string
array by each Length
value from the FileInfo
of each file.foreach
-loop to print out all the file names sorted by their lengths.using System; using System.IO; using System.Linq; // Step 1: get file names with GetFiles. const string dir = "programs/"; string[] files = Directory.GetFiles(dir); // Step 2: order by size. var sorted = from f in files orderby new FileInfo(f).Length descending select f; // Step 3: list files. foreach (string name in sorted) { Console.WriteLine(name); }programs/words.txt programs/search-perls.txt ...
In the C# language, using the LINQ extensions is often the easiest and simplest way to sort things. It is easy to sort with a computed value like the FileInfo
Length
.
In complex applications, we can store the file metadata in object models. But not all applications are complex and this code is useful for small tasks.