0

this is my code

Dim orderedFiles = New System.IO.DirectoryInfo(dir).GetFiles("file_*.jpeg").OrderBy(Function(x) x.Name)

For Each f As System.IO.FileInfo In orderedFiles
msgbox(f.name)
Next

display

file_1.jpeg
file_10.jpeg
file_11.jpeg
file_12.jpeg
file_13.jpeg
file_14.jpeg
file_2.jpeg
file_3.jpeg
file_4.jpeg
file_5.jpeg
file_6.jpeg
file_7.jpeg
file_8.jpeg
file_9.jpeg

i want them to sort 1 - 2 - 3 ...... 14
how can i do it?

10
  • What order do you get if you don;t explicitly sort them? Commented Apr 22, 2020 at 17:04
  • 1
    They are already sorting correctly. They're being sorted by their ASCII values, so 1 followed by 10 is the correct order. The usual way to fix this issue is to add zeros on the left of the numbers that are a single digit, as in 01, which will allow them to sort in the order you want. If that doesn't work for you, you're going to have to write your own code to do the sorting. Commented Apr 22, 2020 at 17:05
  • 1
    I believe the API of interest is StrCmpLogicalW. Commented Apr 22, 2020 at 17:08
  • 1
    I couldn't find a VB.Net example here at SO, but Google found one at bytes.com/topic/visual-basic-net/answers/… Commented Apr 22, 2020 at 17:18
  • 1
    problem solved! i set every file name padleft 000000 e.g 000001 and 000010 now everything is fine. thank you everyone Commented Apr 22, 2020 at 17:52

2 Answers 2

4

You can do what you want without changing the file names using the StrCmpLogicalW API, e.g.

Imports System.IO
Imports System.Runtime.InteropServices

Module Module1

    <DllImport("shlwapi.dll", CharSet:=CharSet.Unicode)>
    Private Function StrCmpLogicalW(x As String, y As String) As Integer
    End Function

    Sub Main()
        Dim files = New DirectoryInfo("D:\johnm\Documents\Test").GetFiles()

        Array.Sort(files,
                   Function(file1, file2) StrCmpLogicalW(file1.Name, file2.Name))

        For Each file In files
            Console.WriteLine(file.Name)
        Next

        Console.ReadLine()
    End Sub

End Module
Sign up to request clarification or add additional context in comments.

Comments

0

problem solved! i just set every file name with padleft 000000
e.g 000001 and 000010 now everything is fine

code

Dim test1 As String = "1"
test1 = test1.ToString.PadLeft(6, "0"c)

display

000001

2 Comments

Can you explain how this worked with New System.IO.DirectoryInfo(dir).GetFiles("file_*.jpeg")?
@Enigmativity, I was wondering the same thing. I can only assume that the OP is referring to how the files were created in the first place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.