Use Path.GetDirectoryName() method to get the given path parent directory.
The good thing about this method instead of the one @jms suggested, is it doesn’t construct any large objects (e.g. FileInfo) but instead it directly gets the exact path.
you can use Path.GetDirectoryName() Like this:
string parent_directory_path, second_parent_dir_path;
// Get our file's parent directory
parent_directory_path = Path.GetDirectoryName(@"C:\\MyDirectory\Second Directory\File.txt");
// Get the directory's own parent directory
second_parent_dir_path = Path.GetDirectoryName(parent_directory_path);
When executing that program you will get this output:
I personally prefer the approach @isoftech suggested, Since it doesn’t require much CPU/Memory resources thus it’s best for performance.
but another even a better approach would be:
Why don’t you Parse Path string on your own?!
Something like this would do:
string my_file_path = @"C:\\MyDir\MyFiles\MyFile.txt";
/* So to get the parent directory we can simply implement this method */
public string get_parent_dir_path(string path)
{
// notice that i used two separators windows style "\\" and linux "/" (for bad formed paths)
// We make sure to remove extra unneeded characters.
int index = path.Trim('/', '\\').LastIndexOfAny(new char[]{'\\', '/'});
// now if index is >= 0 that means we have at least one parent directory, otherwise the given path is the root most.
if (index >= 0)
return path.Remove(index);
else
return "";
}
Doing:
get_parent_dir_path(my_file_path);
should return : "C:\\MyDir\MyFiles"
Note: We can also trim given & returned paths to avoid bad formatted paths.