0
Reply

How to retrieve a proper cased filename.

Ross Pickard

Ross Pickard

Jan 13 2010 8:05 PM
2.3k
The case of the path and filename returned by the System.Directory class uses the case you provide in the Path parameter rather than the true Path & Filename as it is written on the disk - enter the path in small case and it comes back as small case.  I found a class in C# that almost worked but for those of use using VB.Net nothing really exists so ... here is a  function to do the business.  It doesn't handle UNC paths so someone might want to play with it.


    Private Function GetCasedFileName(ByVal FullPath As String) As String
        Dim CasedName As String = ""
        Dim isFile As Boolean = File.Exists(FullPath)
        Dim isDir As Boolean = Directory.Exists(FullPath)
        Dim TestDir As String = ""
        Dim TestFile As String = ""

        If Not isFile And Not isDir Then
            Return ""
            Exit Function
        End If

        If isFile Then
            TestDir = Path.GetDirectoryName(FullPath)
            TestFile = Path.GetFileName(FullPath)
        Else
            TestDir = FullPath
        End If

        ' Find the Root Drive
        If TestDir.StartsWith("\\") Then
            ' Unc Path - how do you resolve the real machine name?
        Else
            CasedName = TestDir.Substring(0, 3).ToUpper
        End If

        Do While CasedName.ToUpper <> TestDir.ToUpper
            Dim DirList() As String = Directory.GetDirectories(CasedName)
            For Each DirName As String In DirList
                If (TestDir.ToUpper & "\").StartsWith(DirName.ToUpper & "\") Then
                    CasedName = DirName
                    Exit For
                End If
            Next
        Loop

        If isFile Then
            Dim FileList() As String = Directory.GetFiles(CasedName)
            For Each FileName As String In FileList
                If FileName.ToUpper = (FullPath.ToUpper) Then
                    CasedName = FileName
                End If
            Next
        End If

        Return CasedName

    End Function