简体   繁体   English

无法通过某些字符串关键字过滤Directory.Getfiles

[英]Unable to filter Directory.Getfiles by Certain string keywords

I'm trying to list out a file with .TXT extension and also only show file containing "EUROPE_" into a listbox 我正在尝试列出扩展名为.TXT的文件,并且也仅将包含“ EUROPE_”的文件显示到列表框中

private void btnDisplay_Click(object sender, EventArgs e)
{            
    listBox1.Items.Clear();
    var files = Directory.EnumerateFiles("C:\\temp\\FOLDER", "*.*", 
        SearchOption.AllDirectories)
        .Where(s =>  s.Contains("*EUROPE*") || s.EndsWith(".TXT"));
}

Nothing displayed when I click the button 当我点击按钮时什么也没显示

You'll need to some adjustments in your code but it's not a bad start. 您需要对代码进行一些调整,但这并不是一个不好的开始。
First of all you can just use the built in wildcard to only get txt-files. 首先,您可以使用内置的通配符仅获取txt文件。 Then you can use the Where to determine which file contains "europe". 然后你可以用Where ,以确定哪些文件包含“欧洲”。 After that you'll need to add each file to the listbox. 之后,您需要将每个文件添加到列表框中。 Otherwise you obviously won't see them. 否则,您显然不会看到它们。

private void btnDisplay_Click(object sender, EventArgs e)
{
    listBox1.Items.Clear();
    var files = Directory.EnumerateFiles("C:\\temp\\FOLDER", "*.txt", SearchOption.AllDirectories)
    .Where(s => s.ToUpper().Contains("EUROPE"));

    foreach(string file in files){
        listBox1.Items.Add(file);
    }
}

Edit: 编辑:
You can indeed use the wildcard also to check if it contains europe. 您确实也可以使用通配符来检查它是否包含欧洲。 In my opinion it's also cleaner and more readable so use this (you'll still need the rest of the code other than this line of course). 在我看来,它也更干净,更易读,因此使用它(当然,除了这一行之外,您还需要其余代码)。 See this answer which shows this exact method just without the code around it. 请参见此答案该答案显示了确切的方法,而没有周围的代码。

You don't have to use the where clause. 您不必使用where子句。 The following line of code should work: 以下代码行应该起作用:

var files = Directory.EnumerateFiles("C:\\temp\\FOLDER", "*EUROPE_*.txt", SearchOption.AllDirectories)

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

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