在C#中使用/或\\文件夹路径 [英] Using / or \\ for folder paths in C#

查看:450
本文介绍了在C#中使用/或\\文件夹路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中编写文件路径时,我发现我可以写C:\或C:/,并获得相同的路径。推荐哪一个?我听说某个地方比使用\(以\作为转义的顺序)更为推荐。

解决方案

Windows支持两个路径分隔符,因此两者都可以工作,至少对于本地路径(/不适用于网络路径)。事实是,在Windows上使用工作但非标准的路径分隔符(/)没有实际的好处,特别是因为您可以使用逐字字符串文字:

  string path = @C:\//看ma,没有逃避

我可以看到使用/ separator的好处的唯一的情况是当你只使用相对路径,并且会使用Windows和Linux中的代码。那么你可以将../foo/bar/baz指向同一个目录。但即使在这种情况下,最好离开System.IO命名空间( Path.DirectorySeparatorChar Path.Combine )来处理这些问题。


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#中使用/或\\文件夹路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆