Get parent directory of parent directory

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

Answers


You can use the System.IO.DirectoryInfo class:

DirectoryInfo networkDir=new DirectoryInfo(@"\\Path\here\now\username");
DirectoryInfo twoLevelsUp=networkDir.Parent.Parent;

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!


I ran into a similar situation. Looks like you could just call GetDirectoryName twice!

var root = Path.GetDirectoryName( Path.GetDirectoryName( path ) );

Viola!


You could try this (I use it in my command lines / batch files all the time).

string twolevelsup = Path.Combine("\\\\networkLocation\\staff\\users\\username", "..\\..\\"); 

Need Your Help

How to make UILabel wordwrap

iphone objective-c cocoa-touch

Is there anyway of making a UILabel wrap to the next line or do I have to use a UITextView?

Remotely debugging my node app that is hosted on AWS

node.js debugging amazon-web-services

I would like to connect to my node server running in debug mode on AWS (node --debug app.js) from my development machine, and be able to debug my app remotely.