Search code examples
c#iodirectoryinfo

Search parent directory from DirectoryInfo


Is there any way to search for the particular parent directory?

I know I can get the parent of the directory using this

Directory.GetParent(Directory.GetCurrentDirectory()).FullName

But this returns immediate parent, is there any way I can kind of search for particular parent in the directory hierarchy of the path?

EDIT

What I am trying to achieve is, say if I have current directory like this

C:/Project/Source/Dev/Database

So I want to reach to the directory Source I know I can reach it by calling GetParent method twice but this I don't think is the right way to do it because what if in future my file current directory changes and it goes further down. So I want some full proof way where I can directly find the path of the directory Source no matter how deep I am in the current directory because that is for sure that I will be inside directory Source

So something like

FindParent('Source')

Solution

  • Actually I thought there is an already existing way or function but if I have to write it myself then this solution I wrote worked for me

        private static string GetParent(string directoryPath, string parent)
        {
            DirectoryInfo directory = new DirectoryInfo(directoryPath);
            while (directory.Parent!=null)
            {
                if (directory.Parent.Name.ToLower() == parent.ToLower())
                {
                    return directory.Parent.FullName;
                }
    
                directory = directory.Parent;
            }
    
            return null;
        }