Vb.net 如何在一个目录中同时搜索多个文本文件以获取一个文本字符串

Vb.net 如何在一个目录中同时搜索多个文本文件以获取一个文本字符串,vb.net,winforms,search,Vb.net,Winforms,Search,我有一个列表框,其中包含一定数量的项目。 对于列表框中的每个项目,文件目录中都存在相应的文本文件 我需要搜索每个文本文件(基于列表框中的内容)中的人名。每个文本文件可能包含名称,也可能不包含名称。 然后我想返回包含名称的文本文件 我尝试过用这种方法来搜索文本文件:它是有效的,但我不确定如何根据列表框中的内容来重复这种方法 Dim sFileContents As String = String.Empty If (System.IO.File.Exists((Application.Startu

我有一个列表框,其中包含一定数量的项目。
对于列表框中的每个项目,文件目录中都存在相应的文本文件

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

我尝试过用这种方法来搜索文本文件:它是有效的,但我不确定如何根据列表框中的内容来重复这种方法

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

另外,如果可以忽略大小写,那就太好了。

如果目录中有一堆文件,并且列表框中有它们的名称,并且希望搜索它们的内容以查找某些内容

一行查询:

Imports System.IO
'...
副检察官()
Dim dir=My.Application.Info.DirectoryPath
Dim ext=“.txt””如果在列表中修剪扩展名。
Dim find=TextBox4.Text
Dim files=Directory.EnumerateFiles(dir).Where(函数x)ListBox1.Items.Cast(字符串的形式)。
Any(函数(y)String.Concat(y,ext)。
等于(Path.GetFileName(x),
StringComparison.InvariantCultureIgnoreCase)和ALSO文件.ReadLines(x)。
任意(函数(z)z.IndexOf(find,StringComparison.InvariantCultureIgnoreCase)>=0)).ToList
ListBox2.Items.Clear()
ListBox2.Items.AddRange(files.Select(函数(x)路径.GetFileNameWithoutExtension(x)).ToArray)
端接头
或者,如果您更喜欢每个循环的

Sub调用者()
Dim dir=My.Application.Info.DirectoryPath
Dim find=TextBox4.Text
将文件变暗为新列表(字符串)
对于ListBox1.Items.Cast(字符串的)中的每个f As字符串。
选择(函数(x)Path.Combine(dir,$“{x}.txt”))
如果文件.Exists(f)和
File.ReadLines(f).Any(函数x)x.IndexOf(find,
StringComparison.InvariantCultureInogoreCase)-1)然后
文件。添加(f)
如果结束
下一个
ListBox2.Items.Clear()
ListBox2.Items.AddRange(files.Select(函数(x)路径.GetFileNameWithoutExtension(x)).ToArray)
端接头

无论哪种方式,文件列表都包含匹配项(如果有)。

加上一个伪并行异步方法,用于非常繁重的名称搜索。
异步函数SearchNameInTextFiles
返回一个命名元组:

(FileName As String, Index As Integer)
其中,
文件名
是解析的文件,
索引
是指定名称(
名称
)第一次出现的位置。
如果未找到匹配的子字符串,则索引值设置为
-1

区分大小写
参数允许指定匹配是否应该区分大小写

您可以从
按钮开始搜索。单击
异步
处理程序(或类似程序),如下所示

Imports System.IO
Imports System.Threading.Tasks

Private Async Sub btnSearchFiles_Click(sender As Object, e As EventArgs) Handles btnSearchFiles.Click
    Dim filesPath = [Your files path]
    Dim theName = textBox4.Text ' $" {textBox4.Text} " to match a whole word
    Dim ext As String = ".txt"  ' Or String.Empty, if extension is already included

    Dim tasks = ListBox1.Items.OfType(Of String).
        Select(Function(f) SearchNameInTextFiles(Path.Combine(filesPath, f & ext), theName, False)).ToList()
    Await Task.WhenAll(tasks)

    Dim results = tasks.Where(Function(t) t.Result.Index >= 0).Select(Function(t) t.Result).ToList()
    results.ForEach(Sub(r) Console.WriteLine($"File: {r.FileName}, Position: {r.Index}"))
End Sub

Private Async Function SearchNameInTextFiles(filePath As String, nameToSearch As String, caseSensitive As Boolean) As Task(Of (FileName As String, Index As Integer))
    If Not File.Exists(filePath) then Return (filePath, -1)
    Using reader As StreamReader = New StreamReader(filePath)
        Dim line As String = String.Empty
        Dim linesLength As Integer = 0
        Dim comparison = If(caseSensitive, StringComparison.CurrentCulture,
                            StringComparison.CurrentCultureIgnoreCase)

        While Not reader.EndOfStream
            line = Await reader.ReadLineAsync()
            Dim position As Integer = line.IndexOf(nameToSearch, comparison)
            If position > 0 Then Return (filePath, linesLength + position)
            linesLength += line.Length
        End While
        Return (filePath, -1)
    End Using
End Function

您可以按照自己的目的执行以下简单步骤:

  • 首先获取应用程序启动目录中的所有文本文件
  • 然后遍历列表框中的所有名称,并针对每个名称搜索所有文本文件以查找包含该名称的文件
  • 为了使过程不区分大小写,我们首先将名称和文本文件的内容转换为“小写”,然后比较它们。以下是完整的代码:

        Private Sub findTextFile()
    
            '1- Get all text files in the directory
            Dim myDirInfo As New IO.DirectoryInfo(Application.StartupPath)
            Dim allTextFiles As IO.FileInfo() = myDirInfo.GetFiles("*.txt")
    
            '2- Iterate over all names in the ListBox
            For Each name As String In ListBox1.Items
    
                'Open text files one-by-one and find the first text file that contains this name
                Dim found As Boolean = False 'Changes to true once the name is found in a text file
                Dim containingFile As String = ""
                For Each file As IO.FileInfo In allTextFiles
                    If System.IO.File.ReadAllText(file.FullName).ToLower.Contains(name.ToLower) Then 'compares case-insensitive
                        found = True
                        containingFile = file.FullName
                        Exit For
                    End If
                Next
    
                'Found?
                If found Then
                    MsgBox("The name '" + name + "' found in:" + vbNewLine + containingFile)
                Else
                    MsgBox("The name '" + name + "' does not exist in any text file.")
                End If
            Next
        End Sub
    

    我可以问一下为什么数据是在文本文件中吗?使用数据库似乎更有意义,但这取决于文本文件的具体内容。然后如何将匹配项转储到另一个列表框中?此外,这是否假定用于搜索的列表框包含文件扩展名(.txt)?@FarnkD将
    文件
    分配给
    数据源
    属性,如:
    ListBox2.DataSource=files
    ,或将其添加到
    集合:
    ListBox2.Items.AddRange(files.ToArray)
    @FarnkD如果只想列出名称而不想列出全名/路径:
    列表框2.Items.AddRange(files.Select(Function(x)Path.GetFileName(x)).ToArray)
    。。。如果你有一个大的列表,请查看另一个答案。谢谢!太棒了!由此产生的一个问题是,有没有办法将部分文本从一个标签复制到另一个标签?第一个标签是John.Moore,但第二个标签中我想要的是John@FarnkD
    Label2.Text=Label1.Text.Split(“.c”).First