Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# searching using directory class

Tags:

c#

directory

I am writing a software tool which, as part of its main task, must search a directory and its sub directories for a directory with a given name, and save to a string array each file path that terminates with the specified directory name. For example:

                   level_1      level_2      Level_3
RootDirectory ---> folderA ---> folderD ---> FolderF ---> Target
             |            |---> folderE ---> Target
             |            
             |---> folderB ---> Target
             |
             |---> FolderC ---> Target

should pump out:

string[] = {RootDirectory\folderA\FolderD\folderF\Target,  
    RootDirectory\folderA\folderE\Target, 
    Rootdirectory\folderB\Target, 
    RootDirectory\foderC\Target}

Originally I used getDirectories(myPath, "Target", SearchOption.AllDirectories) on a directory info object, but there was an issue. For some reason, it would find the target under folders b and c, and also under folderA>folderD>folderF, but would skip FolderE. Once it found the first occurrence within the sub directory, folderA, it would go on to the next folder at level_1. I should mention that folderD in my real-case was in fact alphabetically sorted before folderE, as it is in this example

so instead I decided to use an IEnumerator and run a where filter to select the files that terminate with the given directory name. This found them all. However, i cannot figure out how to do something like getDirectories().Where(x=>(x.attributes & fileattributes.hidden)==0); on an IEnumerator.

The problem is, I need it to skip hidden SVN directories because it is slowing down the process considerably.

So here is my question: how can I get a collection of all paths within a sub directory that end in a given directory name, and exclude hidden files form the search?

like image 543
Mike Schiraldi Avatar asked Aug 05 '26 10:08

Mike Schiraldi


1 Answers

I created your folder structure in the root of my C:\ and came up with the following code using Linqpad.

string root = "c:\\folderA";
string target = "Target";   
var d = new DirectoryInfo(root);
var x = d.EnumerateDirectories(target, SearchOption.AllDirectories);
x.ToList() // for each element, it's in the the FullName 

The only part missing is ignoring the .svn folders

like image 80
dplante Avatar answered Aug 08 '26 00:08

dplante



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!