简体   繁体   中英

vb.net how to list collection of files in a directory, in reverse alphanumeric order same as File Explorer > Name descending

How can I sort a list of directory filepaths in the same reverse alphanumeric order as in File Explorer name reverse order (when 'name' clicked twice)?

The Array.Sort method doesn't sort the filenames correctly when the number of digits following the "#" is different.

For example, filename "Osopcoz #777 1.TXT" is correctly the 3rd file shown in File Explorer for the directory, when view is name order:

HERE IS FILE EXPLORER WITH CORRECT ORDER....

在此处输入图片说明

But Array.Sort puts this filename at the end of all filenames with two digits that follow the #

HERE IS Array.Sort with incorrect order...
在此处输入图片说明

You can use the native StrCmpLogicalW() function to create your own string comparer. It uses an algorithm called Natural sort , which is the same algorithm that Explorer is using (likely Explorer uses this exact method as well).

To make it sort in descending order you just have to negate the return value of StrCmpLogicalW() .

<SuppressUnmanagedCodeSecurity()> _
Public Class NaturalSortComparer
    Implements IComparer(Of String)

    <DllImport("shlwapi.dll", CharSet:=CharSet.Unicode)> _
    Private Shared Function StrCmpLogicalW(ByVal psz1 As String, ByVal psz2 As String) As Integer
    End Function

    Public Property SortDescending As Boolean = False

    Public Sub New()
    End Sub

    Public Sub New(ByVal SortDescending As Boolean)
        Me.SortDescending = SortDescending
    End Sub

    Public Function Compare(ByVal x As String, ByVal y As String) As Integer Implements IComparer(Of String).Compare
        Dim Result As Integer = StrCmpLogicalW(x, y)
        Return If(Me.SortDescending, -Result, Result)
    End Function
End Class

Usage:

Array.Sort(myArray, New NaturalSortComparer(True)) 'True specifies descending sort order.

Online test: https://dotnetfiddle.net/MfLaZx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM