错误的Directory.GetParent? [英] Bug in Directory.GetParent?
问题描述
我是一个非常怪异的行为的 System.IO.Directory.GetParent
法打在脸上:
字符串路径1 = @C:\富\酒吧;
DirectoryInfo的parent1 = Directory.GetParent(路径1);
Console.WriteLine(parent1.FullName); //打印C:\ FOO,符合市场预期
//注意额外的反斜杠。它应该仍然指向同一个位置,对不对?
字符串PATH2 = @C:\富\酒吧\;
DirectoryInfo的parent2 = Directory.GetParent(路径2);
Console.WriteLine(parent2.FullName); //打印C:\富\吧!
我会认为这是一个错误,但由于1.0这种方法已经在那里,所以我想它会被现在的检测。在另一方面,如果它的设计,我想不出一个合理的解释,这样的设计...
你怎么看?是不是一个错误?如果没有,你怎么解释这种现象?
一些谷歌搜索显示的一些想法:
DirectoryInfo的迪=新的DirectoryInfo(@C:\父\子); Console.WriteLine(di.Parent.FullName);
和
DirectoryInfo的迪=新的DirectoryInfo(@C:\父\子\); Console.WriteLine(di.Parent.FullName);
都返回C:\父
我只能假设
Directory.GetParent(...)
不能假定C:\父\子
是一个目录,而不是有没有文件扩展名的文件。的DirectoryInfo
就可以了,因为你构造对象的方式。
个人我认为是,当有一个反斜杠,该字符串被视为一个路径零文件的目录中(也就是,没有名和扩展名的文件)。显然,那些可以存在(应该有一个链接,但由于某些原因,我无法找到任何东西)。
尝试构建一个的FileInfo
对象从路径2
的。你会看到它的正确构建,已的String.Empty
正如其名和扩展名,不存在并具有 C:\富\酒吧
为目录名
。鉴于此,这种情况是有道理的:对于这种零文件的父对象确实是 C:\富\酒吧
I was hit in the face by a very weird behavior of the System.IO.Directory.GetParent
method:
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 !!!
I would consider it a bug, but this method has been there since 1.0, so I guess it would have been detected by now. On the other hand, if it's as designed, I can't think of a sensible explanation for such a design...
What do you think ? Is it a bug ? If not, how do you explain this behavior ?
Some googling reveals some thoughts:
DirectoryInfo di = new DirectoryInfo(@"C:\parent\child"); Console.WriteLine(di.Parent.FullName);
and
DirectoryInfo di = new DirectoryInfo(@"C:\parent\child\"); Console.WriteLine(di.Parent.FullName);
Both return "C:\parent"
I can only assume
Directory.GetParent(...)
can't assume thatC:\parent\child
is a directory instead of a file with no file extension.DirectoryInfo
can, because you're constructing the object that way.
Personally what I think is that when there is a backslash, the string is treated as a path to the "null file" inside the directory (that is, a file with no name and extension). Apparently, those can exist (there should be a link, but for some reason I can't find anything).
Try constructing a FileInfo
object out of path2
. You'll see it's properly constructed, has String.Empty
as its name and extension, does not exist and has C:\foo\bar
as its DirectoryName
. Given that, the situation makes sense: the parent object for this "null file" is indeed C:\foo\bar
.
这篇关于错误的Directory.GetParent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!