Sort by File SizeSort files by their sizes in bytes using the System.Linq namespace.
This page was last reviewed on Nov 10, 2021.
Sort files, size. Each 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).
Useful. This logic is sometimes useful for categorization and presenting UIs with file lists. Many approaches are possible, but we use the LINQ extension methods.
FileInfo Length
Example. 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.
Detail The program uses the Directory.GetFiles method found in the System.IO namespace.
Tip This is the easiest (and normally the best) way to get a string array containing each file name.
Detail The identifier "fns" is used to reference the string array. An descriptive word would be better style.
using System; using System.IO; using System.Linq; class Program { static void Main() { // Directory of files. const string dir = "C:\\site"; // File names. string[] fns = Directory.GetFiles(dir); // Order by size. var sort = from fn in fns orderby new FileInfo(fn).Length descending select fn; // List files. foreach (string n in sort) { Console.WriteLine(n); } } }
(List of all files in the directory)
Understanding query syntax. We use LINQ syntax to order the string array by each Length value from the FileInfo of each file. We can use any C# expression in the query orderby part.
Summary. We sorted files by their sizes. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 10, 2021 (edit link).
© 2007-2023 Sam Allen.