Using / or \\ for folder paths in C#

后端 未结 5 2025
野的像风
野的像风 2020-12-10 11:13

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 usi

相关标签:
5条回答
  • 2020-12-10 11:31

    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.

    0 讨论(0)
  • 2020-12-10 11:36

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

    0 讨论(0)
  • 2020-12-10 11:41

    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 讨论(0)
  • 2020-12-10 11:51

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

    0 讨论(0)
  • 2020-12-10 11:54

    I write paths in C# like this:

    @"C:\My\Path"

    The @ character turns off \ escaping.

    0 讨论(0)
提交回复
热议问题