How do I find the parent directory in C#?

后端 未结 15 681
旧时难觅i
旧时难觅i 2020-11-29 05:04

I use this code for finding the debug directory

public string str_directory = Environment.CurrentDirectory.ToString();

\"C:\\\\Us

相关标签:
15条回答
  • 2020-11-29 05:18
    IO.Path.GetFullPath(@"..\..")
    

    If you clear the "bin\Debug\" in the Project properties -> Build -> Output path, then you can just use AppDomain.CurrentDomain.BaseDirectory

    0 讨论(0)
  • 2020-11-29 05:21

    To avoid issues with trailing \, call it this way:

      string ParentFolder =  Directory.GetParent( folder.Trim('\\')).FullName;
    
    0 讨论(0)
  • 2020-11-29 05:23
    string parent = System.IO.Directory.GetParent(str_directory).FullName;
    

    See BOL

    0 讨论(0)
  • 2020-11-29 05:23

    This is the most common way -- it really depends on what you are doing exactly: (To explain, the example below will remove the last 10 characters which is what you asked for, however if there are some business rules that are driving your need to find a specific location you should use those to retrieve the directory location, not find the location of something else and modify it.)

    // remove last 10 characters from a string
    str_directory = str_directory.Substring(0,str_directory.Length-10);
    
    0 讨论(0)
  • 2020-11-29 05:25

    You can use System.IO.Directory.GetParent() to retrieve the parent directory of a given directory.

    0 讨论(0)
  • 2020-11-29 05:25

    I've found variants of System.IO.Path.Combine(myPath, "..") to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.

    Path.Combine makes sure you never go wrong with slashes.

    .. behaves exactly like it does everywhere else in Windows. You can add any number of \.. to a path in cmd or explorer and it will behave exactly as I describe below.

    Some basic .. behavior:

    1. If there is a file name, .. will chop that off:

    Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..") => D:\Grandparent\Parent\

    1. If the path is a directory, .. will move up a level:

    Path.Combine(@"D:\Grandparent\Parent\", "..") => D:\Grandparent\

    1. ..\.. follows the same rules, twice in a row:

    Path.Combine(@"D:\Grandparent\Parent\Child.txt", @"..\..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", @"..\..") => D:\

    1. And this has the exact same effect:

    Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..", "..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", "..", "..") => D:\

    0 讨论(0)
提交回复
热议问题