c# - 为什么 Path.Combine 不能正确连接以 Path.DirectorySeparatorChar 开头的文件名?

标签 c# .net file

从 Visual Studio 中的即时窗口:

> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"

看来两者应该是一样的。

旧的 FileSystemObject.BuildPath() 不是这样工作的...

最佳答案

这是一个哲学问题(也许只有 Microsoft 才能真正回答),因为它完全按照文档中的说明进行操作。

System.IO.Path.Combine

“如果 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/

相关文章:

C#成员变量初始化;最佳实践?

c# - 有 Dapper executenonquery 吗?我怎么知道我的更新是否有效?

.net - 在 docker 中执行 "dotnet watch run"不起作用(杀死进程 'dotnet.exe run' : The system cannot find the file specified) 时出错

来自 Matlab 的 .NET 性能

c# - 为什么我的 Task.ContinueWith 不在 .NET 4.5 中执行?

c# - 使用 HtmlAgilityPack 获取嵌套表格单元格

c# - Calendar.GetDayOfWeek() 可以返回 (DayOfWeek)7 吗?

python - 如何在 Python 中以 n 行为一组随机排列文本文件的内容

java - 相当于ImageIO的文件是什么

c++ - 如何在 C++ 上获取文件夹及其子文件夹名称和路径中的所有文件到字符串数组?