Search code examples
c#pathopenfiledialog

How Path.GetDirectoryName Works?


When i use OpenFileDialog to Open file, of course i need to get the file directory and its name to load the file.(to load xml, to access the file i need full path.)

opd is OpenFileDialog

        if (opd.ShowDialog() == true)
        {
            var names = opd.FileNames;

            foreach (string name in names)
            {
                LoadFile(Path.Combine(Path.GetDirectoryName(name), name));
            }
        }

my question is How Path.GetDirectoryName take the path of the File by Just taking the string ?

Path.GetDirectoryName(name)

name is Just string and this method takes its directory by just taking string? . there can be thousands of files with same name inside computer.

ShortQuestion: where is opd refrenced?

Edit:

i thought opd.FileNames just takes name of the files.(because of methods name)

and Also i found something interesting.

LoadFile(Path.Combine(Path.GetDirectoryName(name), name));

this works fine Because Path.Combine will just skip the same part of string.

Ex:

string name = @"C:\Users\Default\xml.xml";
string getDirNameResault= Path.GetDirectoryName(name);// this will be C:\Users\Default

So Path.Combine will be

 Path.Combine(@"C:\Users\Default", @"C:\Users\Default\xml.xml)

witch returns "C:\Users\Default\xml.xml" !


Solution

  • name is Just string and this method takes its directory by just taking string? . there can be thousands of files with same name inside computer.

    name contains the full path, Path.GetDirectoryName() just strips everything after the last directory separator, Path.Combine(Path.GetDirectoryName(name), name) will not do anything useful:

    If path2 includes a root, path2 is returned.

    Just use name directly.