Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent to InStrRev

Tags:

string

c#

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) 
like image 783
Mark Kram Avatar asked Apr 02 '11 06:04

Mark Kram


3 Answers

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.

like image 172
Jonathan Wood Avatar answered Oct 26 '22 13:10

Jonathan Wood


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)  
like image 20
Gabe Avatar answered Oct 26 '22 13:10

Gabe


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

Edit: Clarified example

like image 36
Jesper Palm Avatar answered Oct 26 '22 13:10

Jesper Palm