Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent directory of parent directory

Tags:

c#

I have a string relating to a location on a network and I need to get the directory that is 2 up from this location.

The string could be in the format:

string networkDir = "\\\\networkLocation\\staff\\users\\username";

In which case I would need the staff folder and could use the following logic:

string parentDir1 = Path.GetDirectoryName(networkDir);
string parentDir2 = Path.GetPathRoot(Path.GetDirectoryName(networkDir));

However, if the string is in the format:

string networkDir = "\\\\networkLocation\\users\\username";

I would just need the networkLocation part and parentDir2 returns null.

How can I do this?

Just to clarify: In the case that the root happens to be the directory 2 up from the given folder then this is what I need to return

like image 318
Elliott Avatar asked Jul 18 '12 13:07

Elliott


People also ask

How do I get parent directory in os?

Using os. os. path. abspath() can be used to get the parent directory. This method is used to get the normalized version of the path.

How do I reference a parent directory in Python?

Get the Parent Directory in Python Using the path. parent() Method of the pathlib Module. The path. parent() method, as the name suggests, returns the parent directory of the given path passed as an argument in the form of a string.

How do I go to parent directory in PowerShell?

Use Split-Path Cmdlet to Get the Parent's Parent Directory in PowerShell. The Split-Path cmdlet displays the specified part of a path. It can be a parent folder, subfolder, file name, or file extension. The default is to return the parent folder of the specified path.


2 Answers

You can use the System.IO.DirectoryInfo class:

DirectoryInfo networkDir=new DirectoryInfo(@"\\Path\here\now\username");
DirectoryInfo twoLevelsUp=networkDir.Parent.Parent;
like image 161
Omaha Avatar answered Sep 28 '22 23:09

Omaha


DirectoryInfo d = new DirectoryInfo("\\\\networkLocation\\test\\test");
if (d.Parent.Parent != null) 
{ 
    string up2 = d.Parent.Parent.ToString(); 
}
else 
{ 
    string up2 = d.Root.ToString().Split(Path.DirectorySeparatorChar)[2]; 
}

Is what I was looking for. Apologies for any confusion caused!

like image 44
Elliott Avatar answered Sep 28 '22 22:09

Elliott