How do I get .NET's Path.Combine to convert forward slashes to backslashes?

前端 未结 8 2315
[愿得一人]
[愿得一人] 2021-02-03 16:39

I\'m using Path.Combine like so:

Path.Combine(\"test1/test2\", \"test3\\\\test4\");

The output I get is:

test1/test2\\test3\\te         


        
8条回答
  •  感动是毒
    2021-02-03 17:25

    As others have said, Path.Combine doesn't change the separator. However if you convert it to a full path:

    Path.GetFullPath(Path.Combine("test1/test2", "test3\\test4"))
    

    the resulting fully qualified path will use the standard directory separator (backslash for Windows).

    Note that this works on Windows because both \ and / are legal path separators:

    Path.DirectorySeparatorChar = \
    Path.AltDirectorySeparatorChar = /
    

    If you run on, say, .NET Core 2.0 on Linux, only the forward slash is a legal path separator:

    Path.DirectorySeparatorChar = /
    Path.AltDirectorySeparatorChar = /
    

    and in this case it won't convert backslash to forward slash, because backslash is not a legal alternate path separator.

提交回复
热议问题