Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extract filename ad directory from path 2

Status
Not open for further replies.

JonathonC

Technical User
Aug 18, 2001
43
GB
I have a path (eg. "C:\My Documents\file.txt") and I want to know:
The filename (in this case "file.txt")
The directory (in this case "C:\My Documents\")

How would I do this? It's incredible to think that before computers were invented we had to mess things up ourselves!
 
Here are two examples:
[tt]
Private Sub PathBreakVB(strPath)
Dim PathBreak As Long

PathBreak = InStrRev(strPath, "\")
Debug.Print Mid(strPath, 1, PathBreak)
Debug.Print Right(strPath, Len(strPath) - PathBreak)
End Sub

' Requires that you add a reference to the
' Microsoft Scripting Runtime
Private Sub PathBreakFSO(strPath)
Dim fso As New FileSystemObject

Debug.Print fso.GetParentFolderName(strPath) & "\"
Debug.Print fso.GetFileName(strPath)
End Sub
 
Here you go I just whipped these up :)
Code:
Private Function DirFromPath(Path As String)
Dim Pos As Long
    Pos = InStrRev(Path, "\")
    DirFromPath = Left(Path, Pos)
End Function

Private Function FileFromPath(Path As String)
Dim Pos As Long
    Pos = InStrRev(Path, "\")
    FileFromPath = Right(Path, Len(Path) - Pos)
End Function

Private Sub Form_Load()
Dim FullPath As String
Dim FileName As String
Dim FileDir As String
    FullPath = "C:\My Documents\file.txt"
    FileName = FileFromPath(FullPath)
    FileDir = DirFromPath(FullPath)
    MsgBox "Full Path: " & FullPath & vbCrLf & _
           "File Name: " & FileName & vbCrLf & _
           "Directory: " & FileDir
End Sub
 
Thanks, it's nice to know that whenever I get stuck i've always got Tek-Tips to help me. It's incredible to think that before computers were invented we had to mess things up ourselves!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top