1

I need to get the full path from directories but use an array to exclude certain paths without entering the full path into the array.

I am getting the path of directories like this:

List<string> dirs = di.GetDirectories("vault*", SearchOption.AllDirectories)
.Select(x => x.FullName).ToList();

The directory looks like this: I need to filter based on the parent after C.

C:\A\vault
C:\B\vault
C:\C\vault

I have an array like this:

string[] exclude = new string[] {"A", "B"};

Doing something like below does not work because it will require I enter the full name of the path to exclude in the array, which can get nasty:

dirs.Except(exclude);

How can I do this better so that I can easily update the array without all the extraneous characters of longer paths? Example: Adding an additional path in the future to exclude.

  • Do you want to exclude all path which contain A or B (in your example), would `.contain` not work? – peeyush singh Feb 18 '19 at 08:25
  • I have updated the question to show the structure of the directory. – Advanced Novice Feb 18 '19 at 08:26
  • regex might be the most general approach, but if in your case the exclude directory is always after the root (c:\) then you can build a string using root + values from array and again use contain. – peeyush singh Feb 18 '19 at 08:30
  • You can also implement your own like operator which works similar to the SQL like operator...can see once similar implementation here: https://stackoverflow.com/questions/5374481/like-operator-in-linq – peeyush singh Feb 18 '19 at 08:34
  • Possible duplicate of [How does one extract each folder name from a path?](https://stackoverflow.com/questions/401304/how-does-one-extract-each-folder-name-from-a-path) – mjwills Feb 18 '19 at 08:35

2 Answers2

1

I think this should work just fine:

string[] exclude = new string[] { "A", "B" };

List<string> dirs =
    di
        .GetDirectories("vault*", SearchOption.AllDirectories)
        .Where(x => !exclude.Contains(x.Name))
        .Select(x => x.FullName)
        .ToList();

I've tested it. Note that the Contains being used is against exclude - so this is checking whether the Name exists within the array, it is not doing some form of substring search.


To be a little more robust it might be worth using this:

.Where(x => !exclude.Select(y => y.ToUpperInvariant()).Contains(x.Name.ToUpperInvariant()))
mjwills
  • 23,389
  • 6
  • 40
  • 63
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

You have to changed SearchPattern something like:

 List<string> dirs = di.GetDirectories("C\\Vault*", SearchOption.AllDirectories)
           .Select(x => x.FullName).ToList();

All A and B are excluded already

Vijunav Vastivch
  • 4,153
  • 1
  • 16
  • 30