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

前端 未结 8 2162
[愿得一人]
[愿得一人] 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

    Using .NET Reflector, you can see that Path.Combine doesn't change slashes in the provided strings

    public static string Combine(string path1, string path2)
    {
        if ((path1 == null) || (path2 == null))
        {
            throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
        }
        CheckInvalidPathChars(path1);
        CheckInvalidPathChars(path2);
        if (path2.Length == 0)
        {
            return path1;
        }
        if (path1.Length == 0)
        {
            return path2;
        }
        if (IsPathRooted(path2))
        {
            return path2;
        }
        char ch = path1[path1.Length - 1];
        if (((ch != DirectorySeparatorChar) && (ch != AltDirectorySeparatorChar)) && (ch != VolumeSeparatorChar))
        {
            return (path1 + DirectorySeparatorChar + path2);
        }
        return (path1 + path2);
    }
    

    You can do the same with String.Replace and the Uri class methods to determine which one works best for you.

提交回复
热议问题