
You want to sort a directory of files by each file's size in bytes. Code that does this is sometimes useful for categorization and presenting UIs with file lists. It may also be useful for inputting data into databases.

Here we look at how you can sort files by length using the LINQ extension methods in the C# language. We use the FileInfo class and the Length property on it 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.
This C# program shows how to sort files by their sizes in bytes.
Program that sorts files by size [C#]
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);
}
}
}
Output
(List of all files in the directory)Description. The program text uses the Directory.GetFiles method found in the System.IO namespace. This is the easiest and normally the best way to get a string[] array containing each file name.

Understanding query syntax. We use the special 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. The program then lists the files. The descending contextual keyword is used in this example and you can find more information on this useful keyword.
Descending Keyword
Here we looked at how you can sort files by their sizes using the C# language and its LINQ extensions. In really complex applications, you will store the file metadata in your object models. However, not all applications are complex and this code is useful for small tasks. It avoids expensive file IO by using FileInfo.
Sort Examples