Sort files by name

Hi! I’m trying to get the file’s name sorted by the name ascending. I’m using this expression inside a for each loop

Directory.GetFiles(“filePath”, “*.pdf”).OrderBy(Function (x) Path.GetFileName(x))

This is the UiPath output:

But this is my expected output:

What can i do to have this output?

Hi @guilherme.dias

How about this expression

Directory.GetFiles(“folderPath”).OrderByDescending(Function(x) x.LastWriteTime).ToArray


You may try also this approach:

The main point is that i can not ensure that the user created the files in order. In some cases the file 3 could have been created before file 2, for example.

it has this output as the FullfilePaths are Lexically sorted

In your case we would recommend to setup a more specific sorting using the filename without extension and using some parts from the filename for a numerical sorting.

Can we rely on this pattern digits-digit.digit ?

In some cases the pattern is only digits-digit

Some more illustrations for lexically and numerical sortings

give a try

arrFileNamesSorted =

(From x In Directory.GetFiles("YourPath", "*.pdf")
Let fname = Path.GetFileNameWithoutExtension(x)
Let shlp = New String(fname.Where(Function(s) Char.IsDigit(s) OrElse s.Equals("."c)).ToArray)
Let arrSplit = shlp.Split("."c)
Let arrSort = If(arrSplit.Length = 2, arrSplit, {shlp,"-1"})
Order By CInt(arrSort(0)), CInt(arrSort(1))
Select f=x).toArray
1 Like

Same result :frowning:

I’ve changed just “filepath”. Is there anything else to change?

got the issue and updated the statement above.

Kindly note it is very experimental and maybe can fail on some schenarios. Give a try

1 Like

This time it works. Now i’ll spend some time to understand what exactly each part os this linq query does! thank you!!

some starter help for the understanding:

keep only digits and dots → “3068424.1”
Split on dot into two parts {“3068424”,“1”}
Order it first on CInt(“3068424”), second on CInt(“1”)

do some defensive handlings when no dot is present

thank you @ppr you’re the best!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.