Path.Combine不能正常工作

时间:2014-11-06 12:30:13

标签: c# path

我有

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

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

但请改为"/jhjh/klk"

方法调用有什么问题?

3 个答案:

答案 0 :(得分:1)

Combine会为你添加斜杠,所以只需

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

答案 1 :(得分:1)

来自Path.Combine method;

  

组合路径。如果指定的路径之一是零长度   string,此方法返回另一个路径。 如果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的原因以及那个&#39}为什么CombineNoChecks方法返回path2

答案 2 :(得分:0)

来自documentation

  

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

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

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

相关问题