为什么 Path.Combine 无法正确连接以 Path.DirectorySeparatorChar 开头的文件名?

StackOverflow https://stackoverflow.com/questions/53102

  •  09-06-2019
  •  | 
  •  

来自 即时窗口 在视觉工作室中:

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

看来两者应该是一样的。

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

有帮助吗?

解决方案

这是一个哲学问题(也许只有微软才能真正回答),因为它完全按照文档所述进行操作。

系统.IO.路径.组合

“如果path2包含绝对路径,则此方法返回path2。”

这是实际的组合方法 来自.NET 源。你可以看到它调用了 组合无检查, ,然后调用 路径有根 在路径2上并返回该路径(如果是):

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()。

其他提示

这是反汇编代码 .NET反射器 对于 Path.Combine 方法。检查 IsPathRooted 函数。如果第二个路径是根路径(以 DirectorySeparatorChar 开头),则按原样返回第二个路径。

public static string Combine(string path1, string path2)
{
    if ((path1 == null) || (path2 == null))
    {
        throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
    }
    CheckInvalidPathChars(path1);
    CheckInvalidPathChars(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 + DirectorySeparatorChar + path2);
    }
    return (path1 + path2);
}


public static bool IsPathRooted(string path)
{
    if (path != null)
    {
        CheckInvalidPathChars(path);
        int length = path.Length;
        if (
              (
                  (length >= 1) &&
                  (
                      (path[0] == DirectorySeparatorChar) ||
                      (path[0] == AltDirectorySeparatorChar)
                  )
              )

              ||

              ((length >= 2) &&
              (path[1] == VolumeSeparatorChar))
           )
        {
            return true;
        }
    }
    return false;
}

我想解决这个问题:

string sample1 = "configuration/config.xml";
string sample2 = "/configuration/config.xml";
string sample3 = "\\configuration/config.xml";

string dir1 = "c:\\temp";
string dir2 = "c:\\temp\\";
string dir3 = "c:\\temp/";

string path1 = PathCombine(dir1, sample1);
string path2 = PathCombine(dir1, sample2);
string path3 = PathCombine(dir1, sample3);

string path4 = PathCombine(dir2, sample1);
string path5 = PathCombine(dir2, sample2);
string path6 = PathCombine(dir2, sample3);

string path7 = PathCombine(dir3, sample1);
string path8 = PathCombine(dir3, sample2);
string path9 = PathCombine(dir3, sample3);

当然,所有路径 1-9 最后都应包含等效的字符串。这是我想出的 PathCombine 方法:

private string PathCombine(string path1, string path2)
{
    if (Path.IsPathRooted(path2))
    {
        path2 = path2.TrimStart(Path.DirectorySeparatorChar);
        path2 = path2.TrimStart(Path.AltDirectorySeparatorChar);
    }

    return Path.Combine(path1, path2);
}

我还认为这个字符串处理必须手动完成是非常烦人的,我对这背后的原因很感兴趣。

在我看来这是一个错误。问题在于有两种不同类型的“绝对”路径。路径“d:\mydir\myfile.txt”是绝对路径,即使缺少驱动器号,路径“\mydir\myfile.txt”也被视为“绝对”。在我看来,正确的行为是当第二个路径以目录分隔符开头(并且不是 UNC 路径)时,在第一个路径前面添加驱动器号。我建议您编写自己的辅助包装函数,如果您需要它,它可以具有您想要的行为。

微软软件定义网络:

如果指定路径之一是零长度字符串,则此方法返回另一个路径。如果path2包含绝对路径,则此方法返回path2。

在您的示例中,path2 是绝对的。

下列的 克里斯蒂安·格劳斯' 在他的“我讨厌微软的事情”博客中提出的建议,标题为“Path.Combine 本质上是没用的。”,这是我的解决方案:

public static class Pathy
{
    public static string Combine(string path1, string path2)
    {
        if (path1 == null) return path2
        else if (path2 == null) return path1
        else return path1.Trim().TrimEnd(System.IO.Path.DirectorySeparatorChar)
           + System.IO.Path.DirectorySeparatorChar
           + path2.Trim().TrimStart(System.IO.Path.DirectorySeparatorChar);
    }

    public static string Combine(string path1, string path2, string path3)
    {
        return Combine(Combine(path1, path2), path3);
    }
}

有些人建议命名空间应该发生冲突,...我和 Pathy, ,作为一个轻微的,并避免命名空间冲突 System.IO.Path.

编辑: :添加了空参数检查

由于不知道实际细节,我的猜测是它会尝试像加入相对 URI 一样加入。例如:

urljoin('/some/abs/path', '../other') = '/some/abs/other'

这意味着当您使用前面的斜杠连接路径时,您实际上是将一个碱基连接到另一个碱基,在这种情况下,第二个碱基优先。

这段代码应该可以解决问题:

        string strFinalPath = string.Empty;
        string normalizedFirstPath = Path1.TrimEnd(new char[] { '\\' });
        string normalizedSecondPath = Path2.TrimStart(new char[] { '\\' });
        strFinalPath =  Path.Combine(normalizedFirstPath, normalizedSecondPath);
        return strFinalPath;

原因:

您的第二个 URL 被视为绝对路径, Combine 如果最后一个路径是绝对路径,方法只会返回最后一个路径。

解决方案: 只需删除起始斜杠即可 / 你的第二条路径(/SecondPathSecondPath)。然后它就按照你所排除的那样工作。

考虑到通常如何处理(相对)路径,这在某种程度上实际上是有意义的:

string GetFullPath(string path)
{
     string baseDir = @"C:\Users\Foo.Bar";
     return Path.Combine(baseDir, path);
}

// Get full path for RELATIVE file path
GetFullPath("file.txt"); // = C:\Users\Foo.Bar\file.txt

// Get full path for ROOTED file path
GetFullPath(@"C:\Temp\file.txt"); // = C:\Temp\file.txt

真正的问题是:为什么是路径,以 "\", ,被视为“扎根”?这对我来说也是新的,但是 它在 Windows 上是这样工作的:

new FileInfo("\windows"); // FullName = C:\Windows, Exists = True
new FileInfo("windows"); // FullName = C:\Users\Foo.Bar\Windows, Exists = False

这两种方法应该可以避免您意外连接两个都包含分隔符的字符串。

    public static string Combine(string x, string y, char delimiter) {
        return $"{ x.TrimEnd(delimiter) }{ delimiter }{ y.TrimStart(delimiter) }";
    }

    public static string Combine(string[] xs, char delimiter) {
        if (xs.Length < 1) return string.Empty;
        if (xs.Length == 1) return xs[0];
        var x = Combine(xs[0], xs[1], delimiter);
        if (xs.Length == 2) return x;
        var ys = new List<string>();
        ys.Add(x);
        ys.AddRange(xs.Skip(2).ToList());
        return Combine(ys.ToArray(), delimiter);
    }

这个\的意思是“当前驱动器的根目录”。在您的示例中,它表示当前驱动器根目录中的“test”文件夹。因此,这可以等于“c: est”。

如果您想组合两条路径而不丢失任何路径,可以使用以下命令:

?Path.Combine(@"C:\test", @"\test".Substring(0, 1) == @"\" ? @"\test".Substring(1, @"\test".Length - 1) : @"\test");

或者使用变量:

string Path1 = @"C:\Test";
string Path2 = @"\test";
string FullPath = Path.Combine(Path1, Path2.Substring(0, 1) == @"\" ? Path2.Substring(1, Path2.Length - 1) : Path2);

两种情况都返回“C: est est”。

首先,我评估 Path2 是否以 / 开头,如果为真,则返回不带第一个字符的 Path2。否则,返回完整的 Path2。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top