Wednesday, September 1, 2010

Sorting sub-directories using IComparer in Visual Basic .NET

First we create an IComparer class:

Imports System.IO

Public Class DirectoryCompare
    Implements IComparer

    Public Overridable Overloads Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
        Dim objX As DirectoryInfo = CType(x, DirectoryInfo)
        Dim objY As DirectoryInfo = CType(y, DirectoryInfo)
        Return objX.Name.CompareTo(objY.Name)
    End Function

End Class

And some code showing how to use it:

                    Dim dArray() = New DirectoryInfo("C:\\Results").GetDirectories

                    If Not dArray Is Nothing Then

                        Dim dc As New DirectoryCompare()
                        Dim dirs As ArrayList = New ArrayList(dArray)

                        dim lastDirPath as String = CType(dirs(dArray.Length - 1), DirectoryInfo).FullName

                        'step through
                        For Each dir As DirectoryInfo In dArray


                        'step backwards
                        For idir As Integer = dArray.Length - 1 To 0 Step -1

                            Dim dir As DirectoryInfo = CType(dirs(idir), DirectoryInfo)

                    End If