Path.Combine不能正常工作

问题描述 投票:-2回答:3

我有

string path = "path";
string newPath = Path.Combine(path, "/jhjh/klk");

我希望结果将是newPth = path/"/jhjh/klk"

但是得到"/jhjh/klk"

方法调用有什么问题?

c# path
3个回答
1
投票

Combine会为你添加斜杠,所以就这么做

string newPath = Path.Combine("path", @"jhjh\klk");

1
投票

来自Path.Combine method;

组合路径。如果其中一个指定路径是零长度字符串,则此方法返回另一个路径。如果path2包含绝对路径,则此方法返回path2。

Path.Combine方法implemented as;

public static String Combine(String path1, String path2) {
        if (path1==null || path2==null)
            throw new ArgumentNullException((path1==null) ? "path1" : "path2");
        Contract.EndContractBlock();
        CheckInvalidPathChars(path1);
        CheckInvalidPathChars(path2);

        return CombineNoChecks(path1, path2);
}

这里如何CombineNoChecks方法implemented;

private static String CombineNoChecks(String path1, String 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;
    }

IsPathRooted方法implemented;

public static bool IsPathRooted(String path) {
if (path != null) {

    int length = path.Length;
    if ((length >= 1 && (path[0] == DirectorySeparatorChar || path[0] == AltDirectorySeparatorChar))
#if !PLATFORM_UNIX                       
         || (length >= 2 && path[1] == VolumeSeparatorChar)
#endif
         ) return true;
    }
    return false;
}

在你的情况下(path2/jhjh/klk)这使你的path[0]/。这就是为什么你的path[0] == DirectorySeparatorCharlength >= 1表达式返回true,这就是为什么你的IsPathRooted方法返回true,这就是为什么你的CombineNoChecks方法返回path2


0
投票

来自documentation

如果path2包含绝对路径,则此方法返回path2。

这是你的情景。您将绝对路径作为第二个参数传递,以便返回绝对路径。

也许你的错误在于你将绝对路径作为第二个参数传递,但是要传递相对路径。 "/jhjh/klk"以路径分隔符开头的事实使它成为绝对路径。

© www.soinside.com 2019 - 2024. All rights reserved.