C# 获取父目录的父目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11542218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:12:41  来源:igfitidea点击:

Get parent directory of parent directory

c#

提问by Elliott

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.

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

The string could be in the format:

该字符串可以采用以下格式:

string networkDir = "\\networkLocation\staff\users\username";

In which case I would need the stafffolder and could use the following logic:

在这种情况下,我将需要该staff文件夹并可以使用以下逻辑:

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 networkLocationpart and parentDir2returns null.

我只需要该networkLocation部分并parentDir2返回 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

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

采纳答案by Elliott

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]; 
}

Is what I was looking for. Apologies for any confusion caused!

是我要找的。对造成的任何混乱表示歉意!

回答by Omaha

You can use the System.IO.DirectoryInfo class:

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

DirectoryInfo networkDir=new DirectoryInfo(@"\Path\here\now\username");
DirectoryInfo twoLevelsUp=networkDir.Parent.Parent;

回答by tsells

You could try this (I use it in my command lines / batch files all the time).

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

string twolevelsup = Path.Combine("\\networkLocation\staff\users\username", "..\..\"); 

回答by gameweld

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

我遇到了类似的情况。看起来你只能打电话GetDirectoryName两次!

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

Viola!

中提琴!