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.
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.
var path = "C:\workspace\AccurevTestStream\ComponentB\include";
DirectoryInfo d = new DirectoryInfo(path);
var result = d.Parent.Parent.FullName;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With