Home » c# » C# How do i get the Right(String) based on one character?-Exceptionshub

C# How do i get the Right(String) based on one character?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

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) ?
How to&Answers:

This will return everything after the last instance of the character ‘\’.

var result = MyString.Substring(MyString.LastIndexOf('\') + 1);

Answer:

For a path specifically, you can use Path.GetFileName(String).

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 directory, but C:\directory\ becomes the empty string. (This might be what you want, based on how you phrased the question.)

Answer:

If you don’t mind using a bit of LINQ:

var result = MyString?.Split('\').LastOrDefault();

Answer:

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];

Indices and Ranges