Directory.GetParent中的错误?

Tho*_*que 12 .net base-class-library

我被这个System.IO.Directory.GetParent方法的一个非常奇怪的行为击中了脸:

string path1 = @"C:\foo\bar";
DirectoryInfo parent1 = Directory.GetParent(path1);
Console.WriteLine (parent1.FullName); // Prints C:\foo, as expected

// Notice the extra backslash. It should still refer to the same location, right ?
string path2 = @"C:\foo\bar\";
DirectoryInfo parent2 = Directory.GetParent(path2);
Console.WriteLine (parent2.FullName); // Prints C:\foo\bar !!!
Run Code Online (Sandbox Code Playgroud)

我认为它是一个错误,但这种方法自1.0以来一直存在,所以我想现在已经检测到了.另一方面,如果它是按照设计的,我想不出对这种设计的合理解释......

你怎么看 ?这是一个错误吗?如果没有,你如何解释这种行为?

GSe*_*erg 10

一些谷歌搜索揭示了一些想法:

DirectoryInfo di = new DirectoryInfo(@"C:\parent\child");
Console.WriteLine(di.Parent.FullName);
Run Code Online (Sandbox Code Playgroud)

DirectoryInfo di = new DirectoryInfo(@"C:\parent\child\");
Console.WriteLine(di.Parent.FullName);
Run Code Online (Sandbox Code Playgroud)

两者都返回"C:\ parent"

我只能假设Directory.GetParent(...)不能假设这C:\parent\child是一个目录而不是没有文件扩展名的文件.DirectoryInfo可以,因为你正在以这种方式构建对象.


我个人认为,当存在反斜杠时,该字符串被视为目录内"空文件"的路径(即没有名称和扩展名的文件).显然,那些可以存在(应该有一个链接,但由于某种原因,我找不到任何东西).

尝试构建一个FileInfo对象path2.你会看到它的构造是正确的,String.Empty它的名称和扩展名不存在,并且具有C:\foo\bar它的特征DirectoryName.鉴于此,情况是有道理的:这个"空文件"的父对象确实如此C:\foo\bar.