Get parent directory of parent directory

Viewed 26896

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

4 Answers

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

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

Viola!

Related