searching for multiple keywords using getfiles

139 Views Asked by At

I'm using below code to look for files which carry any of these keywords. For now I could only look for kword1 and if no files found, I start repeating the search for kword2. I'm wondering if there is a more efficient way to look for kword1 or kword2 in the same search. I've been looking on multiple sources and I cant seem to find the way.

Here is what I`ve done so far:

string[] matches = 
    Directory
   .GetFiles(
       path1, 
       "*" + kword1 + "*.txt",SearchOption.AllDirectories
);
1

There are 1 best solutions below

0
IV. On

Here are a couple of tricks you can do using System.Linq. First set up the test run like this:

var directoryToSearch = AppDomain.CurrentDomain.BaseDirectory;

string
    kword1 = "exe",
    kword2 = "pdb";

The Where expression retrieves all the files, then filters them according to kword1 and kword2.

var files = 
    Directory
    .GetFiles(
        directoryToSearch, 
        "*", 
        SearchOption.AllDirectories)
    .Where(filename=> filename.Contains(kword1) || filename.Contains(kword2));

The Select expression selects only the file name portion of the full path.

Console.WriteLine(
    string.Join(
        Environment.NewLine, 
        files.Select(file=>Path.GetFileName(file))));

enter image description here