C # is equivalent to InStrRev

I searched for more than an hour, and I can’t understand in my whole life how to search for a string variable, starting with the right one. I want to do to get the last path folder (right in front of 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 have tried so far:

 string s = "C:\\Windows\System32\\Foo\\Bar\\"; s = agencyName.Substring(s.LastIndexOf("\\") + 1) 
+8
string c #
source share
3 answers

Presumably you want to ignore the last \ in the line, because your VB code searches for all but the last character. Your C # code does not work because it searches the entire string, finding \ as the last character in the string, resulting in your substring returning nothing. You must say LastIndexOf to start with the character before the last, as in VB.

I think the equivalent of your VB code is:

 s = s.Substring(s.LastIndexOf("\\", s.Length - 2) + 1) 
+6
source share

Use strToSearch.LastIndexOf(strToFind); .

EDIT: I see that you updated your question to say that you tried LastIndexOf() . This method works, I have used it many times.

You said you want to get the position where the file name begins. However, your sample path does not contain a file name. (Since it ends with \ , this indicates its directory name.)

As suggested elsewhere, if you really don't want the last \ , you need to specify a starting index to tell LastIndexOf() skip backslashes that you don't want.

+8
source share
 var fullPath = @"C:\foo\bar\file.txt"; var folderName = new FileInfo(fullPath).Directory.Name; //folderName will be "bar" 

Edit: Refined Example

+3
source share

All Articles