Why DirectoryInfo.ToString sometimes returns the FullName(path) and sometimes just the directory-Name? I just noticed it because i've tried to concatenate a parent-directory-name with the directory-name here:
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Administrator\Desktop\unpack\folder1");
DirectoryInfo parentDir = dir.Parent;
var dirAndParent = $"{parentDir}{Path.DirectorySeparatorChar}{dir.Name}";
To my suprise this works and returned the desired part unpack\folder1.
I thought i would need parentDir.Name instead of parentDir, similar to dir.Name. If i remove Name from dir.Name i will get the full-path of the directory. But the parent DirectoryInfo instance just returns the Name.
Where is it documented, what is the difference between both DirectoryInfo instances?
Console.WriteLine("dir.ToString: \t\t" + dir.ToString());
Console.WriteLine("parentDir.ToString: \t" + parentDir.ToString());
Will output the FullName(path) for dir and the Name for parentDir:
dir.ToString: C:\Users\Administrator\Desktop\unpack\folder1
parentDir.ToString: unpack
parentDir.FullName returns also the full path: C:\Users\Administrator\Desktop\unpack
Maybe a bug but certainly a lack of documentation.
The lesson is clear: never use DirectoryInfo.ToString or pass the instance into methods like String.Format(or string interpolation) which uses ToString implicitly if the DirectoryInfo instance was initialized via DirectoryInfo.Parent. Since you often don't know how it was initialized it's better to avoid DirectoryInfo.ToString in general. This bug(inconsistent, non-transparent behaviour) might be fixed in future which would break the code.