在Visual Studio的即时窗口中:
> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
看来它们应该是一样的。
旧的FileSystemObject.BuildPath()不是这样工作的……
在Visual Studio的即时窗口中:
> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
看来它们应该是一样的。
旧的FileSystemObject.BuildPath()不是这样工作的……
当前回答
这是. net Reflector for Path的反汇编代码。结合的方法。检查ispathoot函数。如果第二个路径是根路径(以DirectorySeparatorChar开头),则返回第二个路径。
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);
}
public static bool IsPathRooted(string path)
{
if (path != null)
{
CheckInvalidPathChars(path);
int length = path.Length;
if (
(
(length >= 1) &&
(
(path[0] == DirectorySeparatorChar) ||
(path[0] == AltDirectorySeparatorChar)
)
)
||
((length >= 2) &&
(path[1] == VolumeSeparatorChar))
)
{
return true;
}
}
return false;
}
其他回答
我使用聚合函数强制路径组合,如下所示:
public class MyPath
{
public static string ForceCombine(params string[] paths)
{
return paths.Aggregate((x, y) => Path.Combine(x, y.TrimStart('\\')));
}
}
这段代码应该做到这一点:
string strFinalPath = string.Empty;
string normalizedFirstPath = Path1.TrimEnd(new char[] { '\\' });
string normalizedSecondPath = Path2.TrimStart(new char[] { '\\' });
strFinalPath = Path.Combine(normalizedFirstPath, normalizedSecondPath);
return strFinalPath;
由于不知道实际的细节,我猜测它尝试像连接相对uri那样连接。例如:
urljoin('/some/abs/path', '../other') = '/some/abs/other'
这意味着当您使用前面的斜杠连接路径时,实际上是将一个基底连接到另一个基底,在这种情况下,第二个基底优先。
如果你想在不丢失任何路径的情况下组合这两条路径,你可以使用这个:
?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。
这个\表示“当前驱动器的根目录”。在你的例子中,它指的是当前驱动器根目录中的“test”文件夹。所以,这可以等于"c:\test"。