C
C#2y ago
Thinker

Get directory tree of matching items [Answered]

I've been trying to figure this out for the past two hours to little success. I essentially want a method which takes a file/directory search pattern and which returns a tree structure of all files/directories which matched the pattern. DirectoryInfo.GetFileSystemInfos gets close, but issue is that that method just returns a flat sequence of entries. Additionally, if there happens to be a directory with no matching files but a subdirectory with matching files, then that directory won't be in the list. I've messed around with various Linq things to try make any sense of this but I just can't get anywhere. I really don't want to have to search through every subdirectory manually as that sounds way more expensive than the single GetFileSystemInfos call.
2 Replies
Thinker
Thinker2y ago
So like for instance, *.cs in some basic directory should return
<root>
| Program.cs (file)
| Foo.cs (file)
\ Bar (dir)
\ Baz (dir)
| Far.cs (file)
<root>
| Program.cs (file)
| Foo.cs (file)
\ Bar (dir)
\ Baz (dir)
| Far.cs (file)
I've made a method for getting the parent directories of a file/directory down to a specified root, so I could get [Baz, Bar, <root>] from Far.cs, and I can use this to get every directory which contains a relevant file/directory. You'd expect this to be rather simple but like I legit can't figure this out.
Accord
Accord2y ago
✅ This post has been marked as answered!