在Visual Studio的即时窗口中:

> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"

看来它们应该是一样的。

旧的FileSystemObject.BuildPath()不是这样工作的……


当前回答

这是一个哲学问题(也许只有微软能真正回答这个问题),因为它正在做文档中所说的事情。

System.IO.Path.Combine

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

下面是. net源代码中的实际Combine方法。你可以看到它调用了CombineNoChecks,然后在path2上调用ispathooot,如果是的话返回该路径:

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);
}

internal 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 + DirectorySeparatorCharAsString + path2;
    return path1 + path2;
}

我不知道理由是什么。我想解决方案是剥离(或修剪)DirectorySeparatorChar从第二个路径的开始;也许你可以编写自己的Combine方法,然后调用Path.Combine()。

其他回答

如果你想在不丢失任何路径的情况下组合这两条路径,你可以使用这个:

?Path.Combine(@"C:\test", @"\test".Substring(0, 1) == @"\" ? @"\test".Substring(1, @"\test".Length - 1) : @"\test");

或者用变量:

string Path1 = @"C:\Test";
string Path2 = @"\test";
string FullPath = Path.Combine(Path1, Path2.IsRooted() ? Path2.Substring(1, Path2.Length - 1) : Path2);

这两种情况都返回“C:\test\test”。

首先,我计算Path2是否以/开头,如果为真,返回不带第一个字符的Path2。否则,返回完整的Path2。

这两个方法可以避免您意外地连接两个都有分隔符的字符串。

    public static string Combine(string x, string y, char delimiter) {
        return $"{ x.TrimEnd(delimiter) }{ delimiter }{ y.TrimStart(delimiter) }";
    }

    public static string Combine(string[] xs, char delimiter) {
        if (xs.Length < 1) return string.Empty;
        if (xs.Length == 1) return xs[0];
        var x = Combine(xs[0], xs[1], delimiter);
        if (xs.Length == 2) return x;
        var ys = new List<string>();
        ys.Add(x);
        ys.AddRange(xs.Skip(2).ToList());
        return Combine(ys.ToArray(), delimiter);
    }

从MSDN:

如果指定的路径之一是长度为零的字符串,则此方法返回另一个路径。如果path2包含一个绝对路径,该方法返回path2。

在你的例子中,path2是绝对的。

原因:

第二个URL被认为是一个绝对路径,如果最后一个路径是一个绝对路径,Combine方法只会返回最后一个路径。

解决方案:

只需从第二个路径(/SecondPath到SecondPath)中删除前导斜杠/,它就会正常工作。

删除Path.Combine的第二个参数(path2)中的起始斜杠('\')。