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).
This logic is sometimes useful for categorization and presenting file lists. Many approaches are possible, but we use the LINQ extension methods.
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.
Step 1 The program uses the Directory.GetFiles method found in the System.IO namespace.
Step 3 We use the 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
...
Notes, LINQ. 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.
Summary. 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 17, 2023 (edit).