Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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

  • *Experts*
Posted

If you do it for files only, the beauty of it is that you don't have to do it manually :).

You can use the shared method of the IO.Path class, GetFileName.

Dim path as string = "C:\some folder\somefile.txt"
Dim filename As String = SYstem.IO.Path.GetFileName(path)

Posted

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 I'm planning on using.

 

I've messed around with it using the instr() function, but just can't get it right. Do you know of a way to do this manually?

 

Thanks for your help!

  • *Experts*
Posted

Something like this should help you (don't have time to test it):

'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 won't 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 doesn't error and you get the whole name
Dim filename As String = path.SubString(filenamestart, path.Length - filenamestart)

  • Leaders
Posted

you could also do this as an alternative ...

       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)

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...