Pez
Pez

Reputation: 25

Exclude certain directory names

How to exclude certain directory names when getting them from a directory? I currently have:

Dim dir1 As DirectoryInfo() = dir2.GetDirectories()

I've tried a variation of the example below:

Dim dir1 As DirectoryInfo() = dir2.GetDirectories().Where(Name = Name.Contains("00000000.001"))

Trying to exclude two files names from a process I am going to be running on the rest of the files. Any suggestions would be great. Thanks!

EDIT: Tested Answer provided by Tim using this code:

Dim direct1 As DirectoryInfo
For Each direct1 In dir1
        ListBox2.Items.Add(direct1.Name)
Next

It displayed the two file names that I am currently trying to avoid.

Upvotes: 1

Views: 931

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460238

You could use LINQ, therefore i would prefer DirectoryInfo.EnumerateDirectories.

From MSDN:

The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of DirectoryInfo objects before the whole collection is returned. When you use GetDirectories, you must wait for the whole array of DirectoryInfo objects to be returned before you can access the array.

For example:

Dim dirs As DirectoryInfo() = dir2.EnumerateDirectories().
    Where(Function(dir) dir.Name.Contains("00000000.001")).
    ToArray()

If you instead want to exlude them use Not ...:

Dim dirs As DirectoryInfo() = dir2.EnumerateDirectories().
    Where(Function(dir) Not dir.Name.Contains("00000000.001")).
    ToArray()

If you want to exlude multiple use:

Dim exclude = { "00000000.001", "00000000.002" }

Dim dirs As DirectoryInfo() = dir2.EnumerateDirectories().
    Where(Function(dir) Not exclude.Any(Function(d) dir.Name.Contains(d))).
    ToArray()

Upvotes: 1

Related Questions