I have been searching for over an hour and I can not for the life of me figure out how to search a string variable starting on the right. What I want to do is to get the last folder of a path (right before the file name), In VB6 I would do something like this:
Dim s As String
s = "C:\Windows\System32\Foo\Bar\"
Debug.Print Mid(s, InStrRev(Left(s, Len(s) - 1), "\") + 1)
Here is what I tried so far:
string s = "C:\\Windows\System32\\Foo\\Bar\\";
s = agencyName.Substring(s.LastIndexOf("\\") + 1)
Use strToSearch.LastIndexOf(strToFind);
.
EDIT: I see you updated your question to say you've tried LastIndexOf()
. This method works, I've used it many times.
You said you want to get the position where the filename starts. However, your example path contains no filename. (Since it ends with \
, that indicates it's a directory name.)
As suggested elsewhere, if you don't really want the last \
, then you need to specify the start index in order to tell LastIndexOf()
to skip over the trailing backslashes you don't want.
Presumably you want to ignore the last \
in the string, because your VB code is searching all but the last character. Your C# code isn't working because it's searching the whole string, finding the \
as the last character in the string, causing your substring to return nothing. You have to tell LastIndexOf
to start at the character before the last one just as you did in VB.
I think the equivalent to your VB code would be:
s = s.Substring(s.LastIndexOf("\\", s.Length - 2) + 1)
var fullPath = @"C:\foo\bar\file.txt";
var folderName = new FileInfo(fullPath).Directory.Name;
//folderName will be "bar"
Edit: Clarified example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With