Get text after last "\" in file path string

micropathic

Well-known member
Joined
Oct 23, 2003
Messages
75
How can I get the text to the right of the last backslash ("\") in a file name.

For instance


I would want to get the "test.txt" from the string "C:\Program Files\My App\My Dir\My Dir2\test.txt"

or "test2.txt" from the string "C:\Program Files\My App\My Dir\test2.txt"

TIA
 
If you do it for files only, the beauty of it is that you dont have to do it manually :).
You can use the shared method of the IO.Path class, GetFileName.
Code:
Dim path as string = "C:\some folder\somefile.txt"
Dim filename As String = SYstem.IO.Path.GetFileName(path)
 
Actually, I need a way to do it manually because I am working with a windows ce device and am getting paths from it like "\storage card\directory\file.txt" and am eventually going to compare the file with a corresponding file from the pc like "c:\blah\whatever\file.txt".

What I am doing is loading the value of a directory from the pc and a directory from the windows ce device into their own listboxes and plan to write some code that compares the contents of the two list boxes. But, before I can start comparing them, I need the contents of the listboxes to have a similar naming convention. In this case just the file and extension is what Im planning on using.

Ive messed around with it using the instr() function, but just cant get it right. Do you know of a way to do this manually?

Thanks for your help!
 
Something like this should help you (dont have time to test it):
Code:
Create some path
Dim path As String = "C:\some folder\some file.txt"
Get the index of the last slash, and add 1 so the slash wont be included in the string
dim filenamestart As Integer = path.LastIndexOf("\") + 1
Take a part of the string which starts at the index we got earlier
and set the length to the length of the string - the index we got eariler
so the operation doesnt error and you get the whole name
Dim filename As String = path.SubString(filenamestart, path.Length - filenamestart)
 
you could also do this as an alternative ...
Code:
        Dim length As Integer = "C:\some folder\some file.txt".Split("\").GetUpperBound(0) /// the index of the last \
        Dim path As String = "C:\some folder\some file.txt".Split("\")(length)

        MessageBox.Show(path)
 
Back
Top