Does DirectoryInfo.ToString work differently in parent directories?

Why DirectoryInfo.ToStringsometimes returns FullName(path), and sometimes just directory- Name? I just noticed this because I tried to combine the 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 surprise, this works and returns the desired part unpack\folder1. I thought I needed parentDir.Nameinstead parentDir, similar to dir.Name. If I delete Namefrom dir.Name, I will get the full directory path. But the parent DirectoryInfoinstance just returns Name.

Where is this documented, what is the difference between the instances DirectoryInfo?

Console.WriteLine("dir.ToString: \t\t" + dir.ToString());
Console.WriteLine("parentDir.ToString: \t" + parentDir.ToString());

Print FullName(path) for dirand Namefor parentDir:

dir.ToString:           C:\Users\Administrator\Desktop\unpack\folder1
parentDir.ToString:     unpack

parentDir.FullName also returns the full path: C:\Users\Administrator\Desktop\unpack


, , , , . : DirectoryInfo.ToString , String.Format ( ), ToString , DirectoryInfo DirectoryInfo.Parent. , , DirectoryInfo.ToString . (, ) ​​ , .

+4
2

DirectoryInfo, Microsoft, . internal DirectoryInfo(String fullPath, bool junk) Parent.

Parent:

var dirInfoUsingPublicConstructor = new DirectoryInfo(@"C:\Test");
Console.WriteLine(dirInfoUsingPublicConstructor.ToString());

var ctor = typeof(DirectoryInfo).GetConstructors(BindingFlags.NonPublic 
                                                | BindingFlags.Instance).First();
var dirInfoUsingInternalConstructor = 
            ctor.Invoke(new object[] { @"C:\Test", false }) as DirectoryInfo;
Console.WriteLine(dirInfoUsingInternalConstructor.ToString());

:

C:\Test
Test

, Path.GetFileName . . . .

+6

ToString MSDN, , , .

DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Administrator\Desktop\unpack\folder1");

. Node , . .

0

Source: https://habr.com/ru/post/1681765/


All Articles