Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# get all parent directories from a path up to a point?

Tags:

wpf

c#-4.0

I have a listbox in WPF that automatically gets the FullName of the files listed within the box then will Add those files to a Zip under their specific folder.

For example:

C:\ProgramFiles\Folder1\Folder2\Folder3\Folder4\file.txt

I need to be able to Zip it into its folder up to a specific folder, such as only

\Folder2\Folder3\Folder4\file.txt

How could I do this? I've tried getting the Parent directory, but it only returns the directory the file is in.

like image 715
Dan Avatar asked Feb 23 '23 22:02

Dan


2 Answers

    private static IEnumerable<DirectoryInfo> GetAllParentDirectories(DirectoryInfo directoryToScan)
    {
        Stack<DirectoryInfo> ret = new Stack<DirectoryInfo>();
        GetAllParentDirectories(directoryToScan, ref ret);
        return ret;
    }

    private static void GetAllParentDirectories(DirectoryInfo directoryToScan, ref Stack<DirectoryInfo> directories)
    {
        if (directoryToScan == null || directoryToScan.Name == directoryToScan.Root.Name) 
            return;

        directories.Push(directoryToScan);
        GetAllParentDirectories(directoryToScan.Parent, ref directories);
    }
like image 66
Casper Leon Nielsen Avatar answered Feb 26 '23 12:02

Casper Leon Nielsen


You can use the DirectoryInfo object to get the parent up the chain as far as you need to. If you want to get a the parent directory three levels up you can do something like this:

DirectoryInfo di = new DirectoryInfo(@"C:\ProgramFiles\Folder1\Folder2\Folder3\Folder4\file.txt");
        for(int i = 0; i<3; i++){
            di = di.Parent;
        }

Obviously, you can change how you stop your traversal to meet your exact need. After you have the DirectoryInfo object where you need it then you can do what you need. I'm assuming you will need either the full path or to use the Directory object. To get the full path use FullName property. If for example you wanted all the files in the directory you could do the following:

 string[] fileNames = Directory.GetFiles(di.FullName);
like image 41
Craig Suchanec Avatar answered Feb 26 '23 12:02

Craig Suchanec