我有一个与网络上的位置有关的字符串,我需要从这个位置获取2个目录.
字符串可以采用以下格式:
string networkDir = "\\\\networkLocation\\staff\\users\\username";
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我需要该staff文件夹,并可以使用以下逻辑:
string parentDir1 = Path.GetDirectoryName(networkDir);
string parentDir2 = Path.GetPathRoot(Path.GetDirectoryName(networkDir));
Run Code Online (Sandbox Code Playgroud)
但是,如果字符串的格式为:
string networkDir = "\\\\networkLocation\\users\\username";
Run Code Online (Sandbox Code Playgroud)
我只需要该networkLocation部分并parentDir2返回null.
我怎样才能做到这一点?
只是为了澄清:如果根恰好是给定文件夹中的目录2,那么这就是我需要返回的内容
Oma*_*aha 21
您可以使用System.IO.DirectoryInfo类:
DirectoryInfo networkDir=new DirectoryInfo(@"\\Path\here\now\username");
DirectoryInfo twoLevelsUp=networkDir.Parent.Parent;
Run Code Online (Sandbox Code Playgroud)
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];
}
Run Code Online (Sandbox Code Playgroud)
是我在找什么.对所造成的任何混乱道歉!
我遇到了类似的情况。看来你可以打GetDirectoryName两次电话!
var root = Path.GetDirectoryName( Path.GetDirectoryName( path ) );
Run Code Online (Sandbox Code Playgroud)
中提琴!