Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the System.IO.DirectoryInfo class:

DirectoryInfo networkDir=new DirectoryInfo(@"\Pathhere
owusername");
DirectoryInfo twoLevelsUp=networkDir.Parent.Parent;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...