Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 删除最后几个目录的好方法是什么_C#_.net - Fatal编程技术网

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

C# 删除最后几个目录的好方法是什么,c#,.net,C#,.net,我需要解析我得到的目录字符串并删除最后几个文件夹 例如,当我有以下目录字符串时: C:\workspace\AccurevTestStream\ComponentB\include C:\workspace\AccurevTestStream 我可能需要剪切最后两个Directore以创建新的目录字符串: C:\workspace\AccurevTestStream\ComponentB\include C:\workspace\AccurevTestStream 做这件事的好方法是什么

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

例如,当我有以下目录字符串时:

C:\workspace\AccurevTestStream\ComponentB\include
C:\workspace\AccurevTestStream
我可能需要剪切最后两个Directore以创建新的目录字符串:

C:\workspace\AccurevTestStream\ComponentB\include
C:\workspace\AccurevTestStream
做这件事的好方法是什么?我知道我可以使用string
split
join
,但我认为可能有更好的方法来做到这一点。

您可以尝试:

myNewString = myOriginalString.SubString(0, LastIndexOf(@"\"));
myNewString = myNewString.SubString(0, LastIndexOf(@"\"));
不优雅,但应该有效

编辑:(更加不雅)

string myNewString=myOriginalString;
对于(i=0;i=0)
myNewString=myNewString.SubString(0,LastIndexOf(@“\”);
}

我选择DirectoryInfo类及其父属性


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

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;
}
公共字符串GetParentDirectory(字符串路径,int parentCount){ if(string.IsNullOrEmpty(path)| | parentCount<1) 返回路径; 字符串parent=System.IO.Path.GetDirectoryName(路径); 如果(--parentCount>0) 返回GetParentDirectory(parent,parentCount); 返回父母; } 在这种情况下,您可以使用该类-如果您重复调用,它将切掉最后一条路径:

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
这是怎么回事(对不起,我不知道你决定删除什么的标准是什么)


最简单的方法是:

string path = @"C:\workspace\AccurevTestStream\ComponentB\include"
string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\"));
注意这将上升两个级别。结果将是:
newPath=@“C:\workspace\AccurevTestStream\”

您将如何决定删除多少?它是预先确定的吗?因为它是可变的,所以我会尝试使用
split
join
。不,不是最后一个,我需要剪切一个、两个或多个目录。@5YrsLaterDBA-添加了更不雅观的解决方案。可以被放入一个方法,变成一个扩展,等等。我认为他不打算删除目录,只是想从路径字符串中删除它们。
var di = new System.IO.DirectoryInfo("C:\workspace\AccurevTestStream\ComponentB\include");
while (!deleteDir)
    di = di.Parent;
di.Delete(true);
string path = @"C:\workspace\AccurevTestStream\ComponentB\include"
string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\"));