views:

398

answers:

5

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

+2  A: 

I write paths in C# like this:

@"C:\My\Path"

The @ character turns off \ escaping.

Eric J.
+1  A: 

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.

John Saunders
+5  A: 

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

Peter Alexander
It's too bad that Path.Combine takes only 2 parameters.
Mike C.
+10  A: 

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.

Vinko Vrsalovic
What you're calling "raw string operator" is really "verbatim string literal".
Jay Bazuzi
Thanks for the reply!
DMan
@Jay: "Verbatim string literal operator"? or just "Verbatim string literal"?
Vinko Vrsalovic
Even if you're writing code to use on posix and Windows, you should still use the right one. There are many (third-party) abstractions to make this easy, one such being path_util in Chromium.
jeffamaphone
@jeffamaphone: I agree. That's what I say in the final phrase, but in this case there's no need for third party abstractions.
Vinko Vrsalovic
+11  A: 

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

SolutionYogi
`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`.
280Z28
Oops. Thank you for the correction, I did mean to post about DirectorySeparatorChar.
SolutionYogi
This is the correct solution.
jeffamaphone