如果是带有C#的DirectorySeparatorChar,请删除最后一个字符

时间:2011-05-16 14:56:38

标签: c# string

我需要使用Path.GetFileName()提取路径信息,当输入字符串的最后一个字符是DirectorySeparatorChar('/'或'\')时,此函数不起作用。

我想出了这段代码,但它太冗长了。还有更好的方法吗?

string lastCharString = fullPath.Substring (fullPath.Length-1);
char lastChar = lastCharString[0];

if (lastChar == Path.DirectorySeparatorChar) {
    fullPath = fullPath.Substring(0, fullPath.Length-1);
}

6 个答案:

答案 0 :(得分:51)

fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar);

答案 1 :(得分:11)

// If the fullPath is not a root directory
if (Path.GetDirectoryName(fullPath) != null)
    fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

答案 2 :(得分:3)

while(fullPath.EndsWith(Path.DirectorySeparatorChar.ToString())){
   fullPath = fullPath.Substring(0, fullPath.Length-1);
}

答案 3 :(得分:2)

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

给出:

c:\directory
c:\directory\file.txt
c:\directory

希望它有所帮助。

答案 4 :(得分:0)

fullPath = Path.GetFileName(
    fullPath.Split(
        new [] { Path.DirectorySeparatorChar }, 
        StringSplitOptions.RemoveEmptyEntries
    ).Last()
)

答案 5 :(得分:0)

基于 Marino Šimić's answer and Dima's comment ,这里是一个不会在 C:C:\ 上失败的解决方案:

var newPath = Path.Combine(Path.GetDirectoryName(oldPath) ?? oldPath, Path.GetFileName(oldPath));