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 ?
This is pretty interesting. First when I read this I was pretty sure this would be a bug, but when I thought a little bit longer about it I came to the conclusion that probably the intent is that path should not be a directory but a full or relative path to a file. So
gets interpreted as a path to a file with no name in ...\directory. That's kind of silly, but if we assume that the programmers at Microsoft were expecting a full path to a file, it makes sense not to cover this case.
EDIT:
Note that
give the parent as expected.
I agree with GSerg. Just to add some additional firepower, I'm going to add the following code snippets obtained with Reflector.
The Directory.GetParent function basically just calls the Path.GetDirectoryName function:
The Parent property of the DirectoryInfo basically strips off a trailing slash and then calls Path.GetDirectoryName:
Some googling reveals some thoughts:
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 ofpath2
. You'll see it's properly constructed, hasString.Empty
as its name and extension, does not exist and hasC:\foo\bar
as itsDirectoryName
. Given that, the situation makes sense: the parent object for this "null file" is indeedC:\foo\bar
.