dinbrca dinbrca - 1 year ago 93
C# Question

Sorting directory files and getting the highest file name

I have a directory with 40 files with names from 0 to 39 (for example),
I am trying to get the file with the largest number in its name (which means I need to get "39")
I am trying to sort the directory..
I have tried using the following topics:

c# - How to retrieve list of files in directory, sorted by name

Sorting the result of Directory.GetFiles in C#

Nothing works for me..
I tried each of the methods - using Linq and the others..
and I dunno why..

I get the following result of the sorting (check picture below):
enter image description here

Thanks for the help,

Din Bracha.

Answer Source

It is only logical that they would be sorted that way, you would bring in some semantics to sort it by number, namely parse all the file names to numbers, then sort the files by that.

Something like

files.OrderBy(path => Int32.Parse(Path.GetFileNameWithoutExtension(path)))

Use Last() to get the file with the highest number.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download