Posts Helper class TryFindParentDirectory()
Post
Cancel

Helper class TryFindParentDirectory()

This is a simple recursive helper function and several overloads that locate a parent directory if it exists. Should it not find what your asking for, then it will return the DirectoryInfo starting point of the path you originally provided. You can send it a file or directory path that exists or doesn’t, and it shouldn’t care unless its somehow structurally invalid. Note, the DirectoryInfo object is kind of dumb, if you send it a file path and it didn’t find the parent you requested, then you can expect the returned DirectoryInfo pointing entirely to your file; not its directory. So, if your starting from a filename, then you either need to have established directory norms you can depend on or you need to do System.IO.Path.GetDirectoryName() first.

I realize Null might be the typical, expected or desired output, but that is an easy fix; just delete ?? Path in the below code. Also, the ABC is a generic abbreviation I use for my AgileBIM.Controls project, just change it to whatever will be identifiable to you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespace System.IO
{
    public static class ABC
    {
        public static DirectoryInfo TryFindParentDirectory(string path, string name, bool ignoreCase = true)
        {
            return TryFindParentDirectory(new DirectoryInfo(path), name, ignoreCase);
        }

        public static DirectoryInfo TryFindParentDirectory(FileInfo path, string name, bool ignoreCase = true)
        {
            return TryFindParentDirectory(path.Directory, name, ignoreCase);
        }

        public static DirectoryInfo TryFindParentDirectory(DirectoryInfo path, string name, bool ignoreCase = true)
        {
            return getParentDirectory(path, name, ignoreCase) ?? path;
        }

        private static DirectoryInfo getParentDirectory(DirectoryInfo source, string name, bool ignoreCase)
        {
            if (source.Parent == null)
                return null;
            else if (ignoreCase && source.Parent.Name.ToUpper() == name.ToUpper())
                return source.Parent;
            else if (!ignoreCase && source.Parent.Name == name)
                return source.Parent;
            else
                return getParentDirectory(source.Parent, name, ignoreCase);
        }
    }
}
This post is licensed under CC BY 4.0 by the author.