如何一次在目录中的多个文本文件中搜索文本字符串

问题描述 投票:0回答:1

我有一个带有一定数量项目的列表框,对于列表框中的每个项目,文件目录中都存在一个对应的txt文件。

我需要搜索每个文本文件(基于列表框中的内容)以获取人员姓名。每个文本文件可以包含名称,也可以不包含名称。然后,我想返回包含该名称的文本文件。

我已经尝试过这种方法来搜索文本文件,该方法可以正常工作,但是我不确定如何根据列表框中的内容重复此操作。

Dim sFileContents As String = String.Empty
    If (System.IO.File.Exists((Application.StartupPath) & "\Project_Green.txt")) Then
        sFileContents = (System.IO.File.ReadAllText((Application.StartupPath) & "\Project_Green.txt"))
    End If
    If sFileContents.Contains(TextBox4.Text) Then
        MessageBox.Show("yup")
    Else
        MessageBox.Show("nope")
    End If

此外,如果有可能忽略大小写很好的情况。

谢谢

vb.net search
1个回答
0
投票

如果目录中有一堆文件,并且它们的名称在列表框中,并且您想在其内容中搜索某些内容。

一个班轮查询:

Imports System.IO
'...

Sub TheCaller()
    Dim dir = My.Application.Info.DirectoryPath
    Dim find = TextBox4.Text
    Dim files = Directory.EnumerateFiles(dir).Where(Function(x) ListBox1.Items.Cast(Of String).
             Any(Function(y) y.Equals(Path.GetFileName(x),
             StringComparison.InvariantCultureIgnoreCase) AndAlso File.ReadLines(x).
             Any(Function(z) z.IndexOf(find, StringComparison.InvariantCultureIgnoreCase) >= 0))).
             ToList

    Console.WriteLine(String.Join(ControlChars.NewLine, files))
End Sub

或者,如果您更喜欢For Each循环:

Sub Caller()
    Dim dir = My.Application.Info.DirectoryPath
    Dim find = TextBox4.Text
    Dim files As New List(Of String)

    For Each f As String In ListBox1.Items.Cast(Of String).
        Select(Function(x) Path.Combine(dir, x))

        If File.Exists(f) AndAlso
            File.ReadLines(f).Any(Function(x) x.IndexOf(find, 
                                  StringComparison.InvariantCultureIgnoreCase) <> -1) Then
            files.Add(f)
        End If
    Next

    Console.WriteLine(String.Join(ControlChars.NewLine, files))
End Sub

无论哪种方式,files列表都包含匹配项。

© www.soinside.com 2019 - 2024. All rights reserved.