简体   繁体   English

使用 getfiles 搜索多个关键字

[英]searching for multiple keywords using getfiles

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 .现在我只能寻找kword1 ,如果没有找到文件,我开始重复搜索kword2 I'm wondering if there is a more efficient way to look for kword1 or kword2 in the same search.我想知道是否有更有效的方法可以在同一搜索中查找kword1kword2 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
);

Here are a couple of tricks you can do using System.Linq .以下是您可以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 . Where表达式检索所有文件,然后根据kword1kword2过滤它们。

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. Select表达式仅选择完整路径的文件名部分。

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM