问题描述
在C#中编写文件路径时,我发现我可以写C:\或C:/,并获得相同的路径。推荐哪一个?我听说某个地方比使用\(以\作为转义的顺序)更为推荐。Windows支持两个路径分隔符,因此两者都可以工作,至少对于本地路径(/不适用于网络路径)。事实是,在Windows上使用工作但非标准的路径分隔符(/)没有实际的好处,特别是因为您可以使用逐字字符串文字:
string path = @C:\//看ma,没有逃避
我可以看到使用/ separator的好处的唯一的情况是当你只使用相对路径,并且会使用Windows和Linux中的代码。那么你可以将../foo/bar/baz指向同一个目录。但即使在这种情况下,最好离开System.IO命名空间(,)来处理这些问题。
When writing file paths in C#, I found that I can either write something like "C:\" or "C:/" and get the same path. Which one is recommended? I heard somewhere that using a single / was more recommended than using \ (with \ as an escaped sequence).
Windows supports both path separators, so both will work, at least for local paths (/ won't work for network paths). The thing is that there is no actual benefit of using the working but non standard path separator (/) on Windows, especially because you can use the verbatim string literal:
string path = @"C:\" //Look ma, no escape
The only case where I could see a benefit of using the / separator is when you'll work with relative paths only and will use the code in Windows and Linux. Then you can have "../foo/bar/baz" point to the same directory. But even in this case is better to leave the System.IO namespace (Path.DirectorySeparatorChar, Path.Combine) to take care of such issues.
这篇关于在C#中使用/或\\文件夹路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!