Search code examples
c#system.io.file

Differences between "Path" and "Directory" classes and means


I don't understand the difference between path and directory. Could someone explain to me with examples?

I'm trying to understand how to different classes of system.IO namespace works. But in logicaly I didn't get the mean what is "Path" , what is "Directory". Aren't they both the same thing? Why they divided these 2 thing into two different classes?


Solution

  • Directory is more of a confirmation or assessment of. For example. Does a directory exist providing a string representing the path you are interested in. Create a directory, again, provided a string representing the path.

    var myStrPath = @"C:\Users\Public\SomePath\";
    if( ! Directory.Exists( myStrPath ))
       Directory.Create( myStrPath );
    

    You can also enumerate a given folder looking for more, or cycling through them.

    var df = Directory.GetDirectories(@"C:\");
    foreach (var oneFolder in df)
        MessageBox.Show(oneFolder.ToString());
    

    But you can also use Directory based on RELATIVE Path. For example, where your program is running from, you could do

    if( Directory.Exists( "someSubFolderFromWhereRunning" ))
    

    and not worry about fully qualified path.

    Path allows you to get or manipulate path/file information, such as a relative path above and you want to know its FULL path even though you dont know where your program is running from. This might be good to look for an expected startup check file in the relative directory the app is running from, or writing files out to same working folder.

    You can also get the list of bad characters that are not allowed in a path so you can validate against them in some string.

    For each of them, take a look at the "." reference after you do something like

    var what = System.IO.Directory. [and look at the intellisense] 
    var what2 = System.IO.Path.   [intellisense]
    

    And look at the context. It should make more sense to you seeing it with better context.