在 C# 中使用 / 或 \\ 作为文件夹路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1987950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:26:11  来源:igfitidea点击:

Using / or \\ for folder paths in C#

c#windowsstringpathescaping

提问by Dominic K

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).

在 C# 中编写文件路径时,我发现我可以编写类似“C:\”或“C:/”的内容并获得相同的路径。推荐哪一款?我在某处听说使用单个 / 比使用 \ (使用 \ 作为转义序列)更推荐。

采纳答案by Vinko Vrsalovic

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:

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

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.

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

回答by Eric J.

I write paths in C# like this:

我在 C# 中这样写路径:

@"C:\My\Path"

@"C:\我的\路径"

The @ character turns off \ escaping.

@ 字符关闭 \ 转义。

回答by John Saunders

This isn't a C# issue - it's a Windows issue. Paths in Windows are normally shown with a backslash: C:. In my opinion, that's what you should use in C#. Use @"C:\" to prevent special handling of backslaash characters.

这不是 C# 问题 - 这是 Windows 问题。Windows 中的路径通常用反斜杠显示:C:。在我看来,这就是您应该在 C# 中使用的内容。使用@"C:\" 来防止对反斜杠字符的特殊处理。

回答by Peter Alexander

Use Path.Combineand you don't need to worry about such semantics.

使用Path.Combine并且您无需担心此类语义。

回答by SolutionYogi

Please use Path.DirectorySeparatorCharOR better, as Poita suggested use Path.Combine.

请使用Path.DirectorySeparatorChar或更好,因为 Poita 建议使用Path.Combine