给定代码:
string p = @"C:\Users\Brian";
string p2 = @"\bin\Debug";
string result = Path.Combine(p, p2);//result: \bin\Debug
Console.WriteLine(result);
我希望看到的结果是:
C:\Users\Brian\bin\Debug
然而结果是
\bin\Debug
如果我初始化 p2 = @"bin\Debug";
那么结果就如我们所料。查看 MSDN,这似乎按设计工作:
If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.
IMO,在 .NET 中排除 \
作为根更有意义。据我所知,这不是任何 Windows 操作系统上的有效根目录(\\
可以)。然后我可以组合部分路径,而不用担心部分路径是否以 \
开头。
为什么这个方法被设计为将单个 \
视为根?
最佳答案
Why is this method designed to consider a single \ a root?
因为就其他操作而言,它是根。例如,在命令提示符下:
c:\Users\Jon\Test>dir \
Volume in drive C is Windows8_OS
Volume Serial Number is C058-6ADE
Directory of c:\
或来自 .NET 中的其他文件操作:
using System;
using System.IO;
class Test
{
static void Main()
{
var lines = File.ReadAllLines(@"\Users\Jon\Test\Test.cs");
Console.WriteLine(lines.Length);
}
}
输出:
11
或者来自 Java:
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String path = "\\Users\\Jon\\Test\\Test.java";
// Just to prove that the double backslashes are language escapes...
System.out.println(path);
// Obviously we'd normally clean stuff up...
InputStream stream = new FileInputStream(path);
BufferedReader reader = new BufferedReader
(new InputStreamReader(stream, "utf-8"));
System.out.println(reader.readLine());
}
}
输出:
\Users\Jon\Test\Test.java
import java.io.*;
我敢说原生代码也是如此。
那么,在什么地方 不允许 Windows 允许您以“\”开头的路径来在当前驱动器中建立根目录?
Why is this method designed to consider a single \ a root?
我认为更大的问题是为什么您要使用 \
开始您希望成为相对路径的路径。
关于c# - 来自 path.combine 的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15668856/