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 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.
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
. –
Inanimate I write paths in C# like this:
var path = @"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.
params
keyword. –
Cockalorum 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 backslash characters.
.Net Framework 4.8 (VS 2022)
If I am using this:
string myPath = @"C:\myFile.txt";
It's throw an exception "Access to the path 'C:\myFile.txt' is denied.'"
But When I am creating a folder in C:\ then it is working.
string myPath = @"C:\mie\myFile.txt";
© 2022 - 2024 — McMap. All rights reserved.