从 Visual Studio 中的即时窗口:
> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
看来两者应该是一样的。
旧的 FileSystemObject.BuildPath() 不是这样工作的...
最佳答案
这是一个哲学问题(也许只有 Microsoft 才能真正回答),因为它完全按照文档中的说明进行操作。
“如果 path2 包含绝对路径,则此方法返回 path2。”
Here's the actual Combine method来自 .NET 源代码。你可以看到它调用了CombineNoChecks ,然后调用 IsPathRooted在 path2 上,如果是则返回该路径:
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()。
关于c# - 为什么 Path.Combine 不能正确连接以 Path.DirectorySeparatorChar 开头的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53102/