Alex Rivera | Logout

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

Asked 2011-05-16T14:56:37.760
24

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);
}
Edit
Report

2 Answers

16
// If the fullPath is not a root directory
if (Path.GetDirectoryName(fullPath) != null)
    fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
answered 2012-01-20T06:23:57.560
3
while(fullPath.EndsWith(Path.DirectorySeparatorChar.ToString())){
   fullPath = fullPath.Substring(0, fullPath.Length-1);
}
answered 2011-05-16T15:05:57.240

Your Answer