C# Sort files by natural number ordering in the name?

I know this might be late, but here is another solution which works perfectly

FileInfo[] files = di.GetFiles().OrderBy(file =>
    Regex.Replace(file.Name, @"\d+", match => match.Value.PadLeft(4, '0'))
);

Using Regex replace in the OrderBy Clause:

Regex.Replace(file.Name, @"\d+", match => match.Value.PadLeft(4, '0'))

So what this does is it pads each match of numeric values in the file name with a 0 character to a length of 4 characters:

0-0.jpeg     ->   0000-0000.jpeg
0-1.jpeg     ->   0000-0001.jpeg
0-5.jpeg     ->   0000-0005.jpeg
0-9.jpeg     ->   0000-0009.jpeg
0-10.jpeg    ->   0000-0010.jpeg
0-12.jpeg    ->   0000-0012.jpeg

This only happens in the OrderBy clause, it does not alter the original file name.
You will end up with the order you are looking for.

Leave a Comment