为什么 Path.Combine 不能正确连接以 Path.DirectorySeparatorChar 开头的文件名? [英] Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

查看:63
本文介绍了为什么 Path.Combine 不能正确连接以 Path.DirectorySeparatorChar 开头的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Visual Studio 中的立即窗口:

From the Immediate Window in Visual Studio:

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

看起来它们应该是一样的.

It seems that they should both be the same.

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

The old FileSystemObject.BuildPath() didn't work this way...

推荐答案

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

This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.

System.IO.Path.Combine

如果 path2 包含绝对路径,则此方法返回 path2."

"If path2 contains an absolute path, this method returns path2."

这是 .NET 中的实际结合方法来源.您可以看到它调用 CombineNoChecks,然后调用IsPathRooted 在 path2 上,如果是,则返回该路径:

Here's the actual Combine method from the .NET source. You can see that it calls CombineNoChecks, which then calls IsPathRooted on path2 and returns that path if so:

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;也许可以编写自己的组合方法来执行此操作,然后调用 Path.Combine().

I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine().

这篇关于为什么 Path.Combine 不能正确连接以 Path.DirectorySeparatorChar 开头的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆