c# - 来自 path.combine 的意外行为

标签 c# .net

给定代码:

   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/

相关文章:

c# - 访问基于变量的预格式化字符串

c# - 在锁定中使用异步方法的最佳实践是什么

c# - Entity Framework 6.1.3 : Projection - load children of children directly

c# - 为什么 SortedSet<T>.GetViewBetween 不是 O(log N)?

c# - 在 Visual Studio 调试器中打印漂亮的对象图

c# - 为什么这个枚举声明现在起作用了?

c# - 如何自定义 Windows 窗体的系统菜单?

C# - MysqlDataReader 不读取

.net - .NET 中何时使用锁 vs MemoryBarrier

c#泛型类的具体覆盖