I have this:
MyString = @"C:\Somepath\otherpath\etc\string";
And i need this string (which can be longer than a group of characters)
How can i do something like:
NewString = MyString.Right(string, when last "\" is found) ?
This will return everything after the last instance of the character ‘\’.
var result = MyString.Substring(MyString.LastIndexOf('\') + 1);
For a path specifically, you can use
var MyString = @"C:\Somepath\otherpath\etc\string"; var NewString = Path.GetFileName(MyString);
Despite the name of the method, it also works on directory names, provided they aren’t followed by a trailing backslash. So
C:\directory\ becomes the empty string. (This might be what you want, based on how you phrased the question.)
If you don’t mind using a bit of LINQ:
var result = MyString?.Split('\').LastOrDefault();
Depending on your environment, you might be able to use the new indices and range features that came with C# 8.0
var result = MyString.Split('\')[^1];