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

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

问题描述

在C#中写文件路径时,我发现我可以写类似C:"或C:/"的东西并得到相同的路径.推荐哪一个?我在某处听说使用单个/比使用 (使用 作为转义序列)更推荐使用.

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 支持两种路径分隔符,因此两者都可以使用,至少对于本地路径(/不适用于网络路径).问题是在 Windows 上使用有效但非标准的路径分隔符 (/) 没有实际好处,特别是因为您可以使用逐字字符串文字:

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

我能看到使用/分隔符的唯一好处是当您仅使用相对路径并且将使用 Windows 和 Linux 中的代码时.然后你可以让../foo/bar/baz"指向同一个目录.但即使在这种情况下最好离开 System.IO 命名空间 (Path.DirectorySeparatorChar, Path.Combine) 处理此类问题.

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天全站免登陆