Using / or \\ for folder paths in C#

后端 未结 5 2035
野的像风
野的像风 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.

提交回复
热议问题