Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last character if it's DirectorySeparatorChar with C#

Tags:

I need to extract the path info using Path.GetFileName(), and this function doesn't work when the last character of the input string is DirectorySeparatorChar('/' or '\').

I came up with this code, but it's too lengthy. Is there a better way to go?

string lastCharString = fullPath.Substring (fullPath.Length-1); char lastChar = lastCharString[0];  if (lastChar == Path.DirectorySeparatorChar) {     fullPath = fullPath.Substring(0, fullPath.Length-1); } 
like image 706
prosseek Avatar asked May 16 '11 14:05

prosseek


People also ask

How do you remove the last character of a string in C?

Every string in C ends with '\0'. So you need do this: int size = strlen(my_str); //Total size of string my_str[size-1] = '\0'; This way, you remove the last char.

How do I remove the last 3 characters from a string?

slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.


2 Answers

fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar); 
like image 68
Benjamin Podszun Avatar answered Sep 30 '22 19:09

Benjamin Podszun


// If the fullPath is not a root directory if (Path.GetDirectoryName(fullPath) != null)     fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); 
like image 24
Ryeol Avatar answered Sep 30 '22 18:09

Ryeol