C#中是否有与Python的os.path.normpath等效的函数?
在Python中,我会先拿一个原始字符串,然后把它传给os.path.normpath,这样就能把它变成一个正确的路径名。这个方法会自动处理我需要处理的所有特殊字符,我就不用担心了。在C#中有没有类似的功能呢?
这里有一段Python代码。
myClassProjectPath = os.path.normpath(r"C:\Users\Documents\SharpDevelop Projects\Project With Spaces\MyClass\bin\Debug")
补充说明:我担心斜杠和空格。目前,我是在代码里直接写死路径,但不久之后这个路径会变成用户输入的,所以我无法控制使用“/”还是“\”。
4 个回答
2
试着用 Path.Combine
把路径和空值结合起来,或者用 Path.ChangeExtension
把它改成 Path.GetExtension
的样子。也许这些看起来没用的操作(或者其他方法)能帮你把路径规范化。
除此之外,Path
这个类 似乎没有这个功能。
另外,你也可以自己编写这个功能。根据 Python 的文档:
Normalize a pathname. This collapses redundant separators and up-level references
so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
It does not normalize the case (use normcase() for that). On Windows, it converts
forward slashes to backward slashes. It should be understood that this may change
the meaning of the path if it contains symbolic links!
2
你可以在字符串前面加一个@符号,这样就可以创建一个原样字符串。
3
另外,别忘了看看:
string normalizedPath = Path.GetDirectoryName(path);
这样做也能解决 /
和 \
的问题。