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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 17, 2023 (edit).