我有
string path = "path";
string newPath = Path.Combine(path, "/jhjh/klk");
我希望结果将是newPth = path/"/jhjh/klk"
但是得到"/jhjh/klk"
。
方法调用有什么问题?
Combine会为你添加斜杠,所以就这么做
string newPath = Path.Combine("path", @"jhjh\klk");
组合路径。如果其中一个指定路径是零长度字符串,则此方法返回另一个路径。如果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] == DirectorySeparatorChar
和length >= 1
表达式返回true
,这就是为什么你的IsPathRooted
方法返回true
,这就是为什么你的CombineNoChecks
方法返回path2
。
如果path2包含绝对路径,则此方法返回path2。
这是你的情景。您将绝对路径作为第二个参数传递,以便返回绝对路径。
也许你的错误在于你将绝对路径作为第二个参数传递,但是要传递相对路径。 "/jhjh/klk"
以路径分隔符开头的事实使它成为绝对路径。