Remove the last character if it's DirectorySeparatorChar with C#
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 Director开发者_JS百科ySeparatorChar('/' 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);
}
fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar);
// If the fullPath is not a root directory
if (Path.GetDirectoryName(fullPath) != null)
fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
while(fullPath.EndsWith(Path.DirectorySeparatorChar.ToString())){
fullPath = fullPath.Substring(0, fullPath.Length-1);
}
string path1 = @"c:\directory\";
string path2 = @"c:\directory\file.txt";
string path3 = @"c:\directory";
Console.WriteLine(Path.Combine(Path.GetDirectoryName(path1), Path.GetFileName(path1)));
Console.WriteLine(Path.Combine(Path.GetDirectoryName(path2), Path.GetFileName(path2)));
Console.WriteLine(Path.Combine(Path.GetDirectoryName(path3), Path.GetFileName(path3)));
Gives:
c:\directory
c:\directory\file.txt
c:\directory
Hope it helps.
fullPath = Path.GetFileName(
fullPath.Split(
new [] { Path.DirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries
).Last()
)
Based on Marino Šimić's answer and Dima's comment here is a solution which will not fail on C:
and C:\
:
var newPath = Path.Combine(Path.GetDirectoryName(oldPath) ?? oldPath, Path.GetFileName(oldPath));
精彩评论