获取父目录的父目录
我有一个与网络上的位置相关的字符串,我需要从该位置获取2个目录。
字符串可以采用以下格式:
string networkDir = "\\\\networkLocation\\staff\\users\\username";
在这种情况下,我需要staff
文件夹,可以使用以下逻辑:
string parentDir1 = Path.GetDirectoryName(networkDir); string parentDir2 = Path.GetPathRoot(Path.GetDirectoryName(networkDir));
但是,如果字符串的格式为:
string networkDir = "\\\\networkLocation\\users\\username";
我只需要parentDir2
部分, parentDir2
返回null。
我怎样才能做到这一点?
只是为了澄清:如果根恰好是给定文件夹中的目录2,那么这就是我需要返回的内容
您可以使用System.IO.DirectoryInfo类:
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]; }
是我在找什么。 抱歉引起任何混乱!
我遇到了类似的情况。 看起来你可以两次调用GetDirectoryName
!
var root = Path.GetDirectoryName( Path.GetDirectoryName( path ) );
中提琴!
你可以尝试这个(我一直在我的命令行/批处理文件中使用它)。
string twolevelsup = Path.Combine("\\\\networkLocation\\staff\\users\\username", "..\\..\\");