什么是删除最后几个目录的好方法

5Yr*_*DBA 7 .net c#

我需要解析我得到的目录字符串并删除最后几个文件夹.

例如,当我有这个目录字符串时:

C:\workspace\AccurevTestStream\ComponentB\include
Run Code Online (Sandbox Code Playgroud)

我可能需要剪切最后两个directores来创建一个新的目录字符串:

C:\workspace\AccurevTestStream
Run Code Online (Sandbox Code Playgroud)

这样做的好方法是什么?我知道我可以使用字符串split,join但我认为可能有更好的方法来做到这一点.

Unm*_*kar 14

var path = "C:\workspace\AccurevTestStream\ComponentB\include";    
DirectoryInfo d = new DirectoryInfo(path);
var result = d.Parent.Parent.FullName;
Run Code Online (Sandbox Code Playgroud)


Nat*_*lor 9

这是一个简单的递归方法,假设您知道要从路径中删除多少个父目录:

public string GetParentDirectory(string path, int parentCount) {
    if(string.IsNullOrEmpty(path) || parentCount < 1)
        return path;

    string parent = System.IO.Path.GetDirectoryName(path);

    if(--parentCount > 0)
        return GetParentDirectory(parent, parentCount);

    return parent;
}
Run Code Online (Sandbox Code Playgroud)