StevieB
StevieB

Reputation: 6523

Order files in a folder by numerical value instead of string

Trying something like this to sort all my files in a directory by numerical value of file names not string.

var txtFiles = Directory.GetFiles(outputDirectory, "*.txt").OrderBy(f => int.Parse(f));

filesnames in the folder are like

1.txt
2.txt

etc

But getting error "Input format not in correct format"

Any ideas ?

Upvotes: 0

Views: 677

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

You are trying to parse whole file name to integer (but file name looks like "C:\foo\bar\2.txt"). Use Path.GetFileNameWithoutExtension to get only number part of your file name (for sample name I provided, it returns "2"):

var txtFiles = Directory
                   .GetFiles(outputDirectory, "*.txt")
                   .OrderBy(f => int.Parse(Path.GetFileNameWithoutExtension(f)));

Side note: you can use Directory.EnumerateFiles to avoid file names array creation while enumerating files.

Upvotes: 6

Related Questions