Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is a good way to remove last few directory

Tags:

c#

.net

I need to parse a directory string I get and remove last few folders.

For example, when I have this directory string:

C:\workspace\AccurevTestStream\ComponentB\include

I may need to cut the last two directores to create a new directory string:

C:\workspace\AccurevTestStream

what is a good way to do this? I know I can use string split and join but I think there may be a better way to do this.

like image 716
5YrsLaterDBA Avatar asked Dec 08 '10 16:12

5YrsLaterDBA


People also ask

How do I remove a directory in Unix?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.


2 Answers

var path = "C:\workspace\AccurevTestStream\ComponentB\include";    
DirectoryInfo d = new DirectoryInfo(path);
var result = d.Parent.Parent.FullName;
like image 118
Unmesh Kondolikar Avatar answered Sep 20 '22 02:09

Unmesh Kondolikar


Here's a simple recursive method that assumes you know how many parent directories to remove from the path:

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;
}
like image 11
Nathan Taylor Avatar answered Sep 22 '22 02:09

Nathan Taylor