Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude subdirectories in a directory loop

In a .NET code, I have a loop that takes all .wav files from D:\Temp and its subdirectories :

string[] fileHolder = Directory.GetFiles("D:\\Temp","*.wav", SearchOption.AllDirectories);

I want to exclude all .wav files coming from folders that have "blablabla" in their folder name.

How do do this ?

P.S. This is similar to Exclude directories that contain sub directories?, but I haven't been able to use successfully the answers of this topic.

like image 745
Basj Avatar asked Nov 29 '25 06:11

Basj


2 Answers

IEnumerable<string> files = 
   from f in Directory.GetFiles("D:\\Temp", "*.wav", SearchOption.AllDirectories)
   where !Path.GetDirectoryName(f).Contains("blablabla")
   select f;

Adding several conditions:

var files = from f in Directory.GetFiles("D:\\Temp", "*.wav", SearchOption.AllDirectories)
            let directoryName = Path.GetDirectoryName(f)
            where !directoryName.Contains("blablabla") &&
                  !direcotyName.Contains("foo")
            select f;

Another solution: (I think that Path.GetDirectoryName is not fastest possible operation)

public static IEnumerable<string> GetFiles(string path, string searchPattern,
                                           Func<string, bool> dirSelector)
{
    if (!dirSelector(path))
        yield break;

    foreach (var file in Directory.GetFiles(path, searchPattern))
        yield return file;

    foreach (var dir in Directory.GetDirectories(path))
        foreach (var file in GetFiles(dir, searchPattern, dirSelector))
            yield return file;
}

Usage:

Func<string, bool> dirSelector = (d) => !d.Contains("blablabla");
string[] files = GetFiles("D:\\Temp", "*.wav", dirSelector).ToArray();
like image 113
Sergey Berezovskiy Avatar answered Nov 30 '25 18:11

Sergey Berezovskiy


Try following:

string[] fileHolder = Directory.GetFiles(@"d:\temp", "*.wav",
         SearchOption.AllDirectories).Where(file => !file.Contains("blabla")).ToArray();
like image 26
Michal Klouda Avatar answered Nov 30 '25 18:11

Michal Klouda