C# 获取父目录的父目录

C# 获取父目录的父目录,c#,C#,我有一个与网络上某个位置相关的字符串,我需要从这个位置获取2的目录 字符串的格式可以是: string networkDir = "\\\\networkLocation\\staff\\users\\username"; string networkDir = "\\\\networkLocation\\users\\username"; 在这种情况下,我需要staff文件夹,并且可以使用以下逻辑: string parentDir1 = Path.GetDirectoryName(net

我有一个与网络上某个位置相关的字符串,我需要从这个位置获取2的目录

字符串的格式可以是:

string networkDir = "\\\\networkLocation\\staff\\users\\username";
string networkDir = "\\\\networkLocation\\users\\username";
在这种情况下,我需要
staff
文件夹,并且可以使用以下逻辑:

string parentDir1 = Path.GetDirectoryName(networkDir);
string parentDir2 = Path.GetPathRoot(Path.GetDirectoryName(networkDir));
但是,如果字符串的格式为:

string networkDir = "\\\\networkLocation\\staff\\users\\username";
string networkDir = "\\\\networkLocation\\users\\username";
我只需要
networkLocation
部分,并且
parentDir2
返回null

我该怎么做


只是澄清一下:如果根恰好是给定文件夹中的目录2,那么这就是我需要返回的内容

您可以使用System.IO.DirectoryInfo类:

DirectoryInfo networkDir=new DirectoryInfo(@"\\Path\here\now\username");
DirectoryInfo twoLevelsUp=networkDir.Parent.Parent;
这就是我要找的。对于由此造成的任何混乱,我深表歉意

您可以试试这个(我一直在命令行/批处理文件中使用它)


我遇到了类似的情况。看起来您可以调用
GetDirectoryName
两次

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

中提琴

仅供参考:您可以使用@前缀编写文字字符串,以使其更可读/可复制/等等@“\\networkLocation\users\username”。我不太清楚您想从这个问题中做什么。如果字符串的格式为
\\Path\here\username
,则返回null,如果您一直备份到根目录,例如C:\or\\server\share。如果根恰好是给定文件夹上的目录2,那么这就是我需要返回的内容。在处理路径操作时,使用字符串不是一个好主意。考虑使用<代码> DirectoryInfo <代码>