Extract path from path & filename

P

Paul

Hi,

Using the code below I can extract the filename from a path but I would like
to know how to get just the path too.
So if the full path is "C:\A Long Time Ago\In A Galaxy\Far Far
Away\SomeFilename.txt"
The filename is: SomeFilename.txt
The path only is: C:\A Long Time Ago\In A Galaxy\Far Far Away\

I know there's other methods of getting the filename only, path only etc.
that are new to VB.NET but they involve using the FileInfo/DirectoryInfo
classes and for this I prefer to use the InStrRev/Trim method.

Thanks,
Paul

Dim i As Integer
Dim sFilename As String
Dim file As String = "C:\A Long Time Ago\In A Galaxy\Far Far
Away\SomeFilename.txt"

i = InStrRev(file.Trim, "\")
If i = 0 Then
'No path found, only filename
sFilename = file.Trim
Else
'Assign filename only to variable
sFilename = Right(file.Trim, Len(file.Trim) - i)
End If

MsgBox(sFilename)
 
L

Lawrence J. Rizzo

You can use virtually the same code...just change to use the MID function,
retunring the 1st character through the character before the first \ from
the end.
'Assign path only to variable
sPath = Mid(file.Trim, 1, i-1)
 
P

Paul

Thanks Lawrence, that did the job nicely.


Lawrence J. Rizzo said:
You can use virtually the same code...just change to use the MID function,
retunring the 1st character through the character before the first \ from
the end.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top