Extracting Path / Filename from a String

This procedure takes a Windows compatible path and breaks it into the filename with extension and without extension, the extension alone, the path, and whether it’s a valid file or not.


option Explicit

private Type PathInfo
    FileNamewExt as string
    FileNamewoExt as string
    FileExt as string
    FilePath as string
    FileIsValid as Boolean
End Type

private Sub ExtractInfo(Source as string, _
        ReturnInfo as PathInfo)

    Dim intCurrentPos as Integer, intFileNamePos as Integer
    Dim intFileExtPos as Integer

    'clear UDT passed in if there is any existing data
    ReturnInfo.FileExt = ""
    ReturnInfo.FileIsValid = false
    ReturnInfo.FileNamewExt = ""
    ReturnInfo.FileNamewoExt = ""
    ReturnInfo.FilePath = ""

    If Source <> "" then

        'get file name by finding the last slash in the string
        Do
            intCurrentPos = InStr(intCurrentPos + 1, Source, "", _
                            vbTextCompare)
            If intCurrentPos <> 0 then
                intFileNamePos = intCurrentPos
            else
                intFileNamePos = intFileNamePos + 1
                Exit Do
            End If
        Loop

        'get file extension position if any
        intFileExtPos = InStr(intFileNamePos, Source, ".", _
                        vbTextCompare) + 1
        If intFileExtPos = 1 then
            Exit Sub
        End If

        'put data in UDT passed in
        If intFileNamePos <> 1 then
            ReturnInfo.FileNamewExt = mid(Source, intFileNamePos, _
                                      len(Source) - intFileNamePos + 1)
            ReturnInfo.FilePath = mid(Source, 1, _
                                  intFileNamePos - 2)
        End If
        If intFileNamePos <> 1 And intFileExtPos <> 1 then
            ReturnInfo.FileNamewoExt = mid(Source, intFileNamePos, _
                                       intFileExtPos - _
                                       intFileNamePos - 1)
            ReturnInfo.FileExt = mid(Source, intFileExtPos, _
                                 len(Source) - intFileExtPos + 1)
        End If
        If Dir(Source, vbArchive + vbHidden + vbNormal + _
               vbReadOnly + vbSystem) <> "" then
            ReturnInfo.FileIsValid = true
        else
            ReturnInfo.FileIsValid = false
        End If

    End If

End Sub

Download ExtractPath.Bas (2k)

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read