I use this code for finding the debug directory
public string str_directory = Environment.CurrentDirectory.ToString();
\"C:\\\\Us
To get a 'grandparent' directory, call Directory.GetParent() twice:
var gparent = Directory.GetParent(Directory.GetParent(str_directory).ToString());
You might want to look into the DirectoryInfo.Parent
property.
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?
Path.GetDirectoryName(path + "/") ?? ""
will reliably give us a directory path without a trailing slash.
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...
by navigating up.GetDirectoryName
will return null
for an empty path, which we coalesce to ""
.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
.