开发者

Using / or \\ for folder paths in C#

开发者 https://www.devze.com 2022-12-15 09:39 出处:网络
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开发者

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开发者_JAVA百科 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.


Please use Path.DirectorySeparatorChar OR better, as Poita suggested use Path.Combine.


I write paths in C# like this:

@"C:\My\Path"

The @ character turns off \ escaping.

EDIT a decade later

.NET now runs on Linux. Use Path.Combine() where feasible, otherwise use Path.DirectorySeparatorChar to construct a path with \ or / as appropriate to the underlying OS.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消