来自path.combine的意外行为

本文关键字:意外 path combine 来自 | 更新日期: 2023-09-27 18:06:25

给定代码:

   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,这似乎是按照设计工作的:

如果path2不包含根目录(例如,如果path2没有启动)使用分隔符或驱动器规格),结果是两条路径的连接,中间有一个分隔符的性格。如果path2包含根目录,则返回path2。

在我看来,在。net中排除'作为根更有意义。我敢说,这不是一个有效的根在任何windows操作系统(''可以)。然后我可以组合部分路径,而不用考虑部分路径是否以'开头。

为什么这个方法被设计成考虑单个'作为根?

来自path.combine的意外行为

为什么这个方法被设计为考虑单个' a根?

因为就其他操作而言,根。例如,在命令提示符中:

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不允许您以"'"开始一个路径以在当前驱动器中根它吗?

为什么这个方法被设计为考虑单个' a根?

我认为更大的问题是为什么你要用'来开始你想要的相对路径。