How do I find the parent directory in C#?

后端 未结 15 682
旧时难觅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条回答
  • To get a 'grandparent' directory, call Directory.GetParent() twice:

    var gparent = Directory.GetParent(Directory.GetParent(str_directory).ToString());
    
    0 讨论(0)
  • 2020-11-29 05:36

    You might want to look into the DirectoryInfo.Parent property.

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

    Since nothing else I have found helps to solve this in a truly normalized way, here is another answer.

    Note that some answers to similar questions try to use the Uri type, but that struggles with trailing slashes vs. no trailing slashes too.

    My other answer on this page works for operations that put the file system to work, but if we want to have the resolved path right now (such as for comparison reasons), without going through the file system, C:/Temp/.. and C:/ would be considered different. Without going through the file system, navigating in that manner does not provide us with a normalized, properly comparable path.

    What can we do?

    We will build on the following discovery:

    Path.GetDirectoryName(path + "/") ?? "" will reliably give us a directory path without a trailing slash.

    • Adding a slash (as string, not as char) will treat a null path the same as it treats "".
    • GetDirectoryName will refrain from discarding the last path component thanks to the added slash.
    • GetDirectoryName will normalize slashes and navigational dots.
    • This includes the removal of any trailing slashes.
    • This includes collapsing .. by navigating up.
    • GetDirectoryName will return null for an empty path, which we coalesce to "".

    How do we use this?

    First, normalize the input path:

    dirPath = Path.GetDirectoryName(dirPath + "/") ?? "";
    

    Then, we can get the parent directory, and we can repeat this operation any number of times to navigate further up:

    // This is reliable if path results from this or the previous operation
    path = Path.GetDirectoryName(path);
    

    Note that we have never touched the file system. No part of the path needs to exist, as it would if we had used DirectoryInfo.

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