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).
-
Thanks to John Saunders for pointing out this is a Windows issue. I heard using / is better for cross-compatibility, which doesn't matter too much here as I'm targeting Windows.Dominic K– Dominic K2010-01-01 05:48:41 +00:00Commented Jan 1, 2010 at 5:48
-
Bug in title: should be "/ or \\", not "// or \".sblom– sblom2010-01-01 13:16:19 +00:00Commented Jan 1, 2010 at 13:16
-
2@sblom- Not sure the exact difference, but fixed since it works :pDominic K– Dominic K2010-01-01 19:38:23 +00:00Commented Jan 1, 2010 at 19:38
6 Answers
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.
6 Comments
Please use Path.DirectorySeparatorChar OR better, as Poita suggested use Path.Combine.
2 Comments
Path.PathSeparator is a character to split paths in the PATH environment variable. On Windows it is ;. I updated this answer to refer to DirectorySeparatorChar.