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

pro*_*eek 22 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);
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*zun 54

fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar);
Run Code Online (Sandbox Code Playgroud)

  • 同意,谢谢.在这种情况下可能是`TrimEnd(Path.DirectorySeparatorChar,Path.AltDirectorySeparatorChar)`(以避免迭代字符串两次). (7认同)
  • 这不适用于备用目录路径分隔符.在此之后你应该执行一个fullPath.TrimEnd(Path.AltDirectorySeparatorChar),以便在路径上没有错误:"c:/ path /" (3认同)

Rye*_*eol 14

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

  • 这应该是最佳答案。 (2认同)
  • 嗯,实际上它应该,因为它留下了@"C:\" 就像我真正喜欢的那样。 (2认同)