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

时间:2010-12-08 16:27:26

标签: c# .net

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

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

C:\workspace\AccurevTestStream\ComponentB\include

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

C:\workspace\AccurevTestStream

这是一个很好的方法吗?我知道我可以使用字符串splitjoin,但我认为可能有更好的方法来执行此操作。

8 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分: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;
}

答案 2 :(得分:3)

在这种情况下,您可以使用System.IO.Path课程 - 如果您反复拨打Path.GetDirectoryName,它会切断最后一条路径:

string path = @"C:\workspace\AccurevTestStream\ComponentB\include";
path = Path.GetDirectoryName(path); //returns C:\workspace\AccurevTestStream\ComponentB
path = Path.GetDirectoryName(path); //returns C:\workspace\AccurevTestStream
//etc

答案 3 :(得分:1)

您可以尝试:

myNewString = myOriginalString.SubString(0, LastIndexOf(@"\"));
myNewString = myNewString.SubString(0, LastIndexOf(@"\"));

不优雅,但应该有效。

编辑(更不优雅)

string myNewString = myOriginalString;
for(i=0;i<NumberToChop;i++)
{
    if(LastIndexOf(@"\") > 0)
        myNewString = myNewString.SubString(0, LastIndexOf(@"\"));
}

答案 4 :(得分:1)

我会使用DirectoryInfo类及其Parent属性。

http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx

答案 5 :(得分:1)

    static String GoUp(String path, Int32 num)
    {
        if (num-- > 0)
        {
            return GoUp(Directory.GetParent(path).ToString(), num);
        }
        return path;
    }

答案 6 :(得分:0)

最简单的方法:

string path = @"C:\workspace\AccurevTestStream\ComponentB\include"
string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\"));

注意这有两个等级。结果将是:     newPath = @"C:\workspace\AccurevTestStream\";

答案 7 :(得分:-1)

这是怎么回事(对不起,我不知道你的标准是什么,以确定删除什么)......

var di = new System.IO.DirectoryInfo("C:\workspace\AccurevTestStream\ComponentB\include");
while (!deleteDir)
    di = di.Parent;
di.Delete(true);