BP Forums
How to search multiple files for one string - Printable Version

+- BP Forums (https://bpforums.info)
+-- Forum: Archived Forums (https://bpforums.info/forumdisplay.php?fid=55)
+--- Forum: Archived Forums (https://bpforums.info/forumdisplay.php?fid=56)
+---- Forum: VB.NET (Visual Basic 2010/2008) (https://bpforums.info/forumdisplay.php?fid=8)
+---- Thread: How to search multiple files for one string (/showthread.php?tid=547)



How to search multiple files for one string - ryan - 06-18-2012

I am trying to make an app that will search multiple files for one string. I am able to make it search an individual file with the following code:

Dim numberinfile As String = IO.File.ReadAllText("C:\Documents and Settings\Owner\My Documents\Downloads\example.txt")
Dim target_string As String = TextBox1.Text

If numberinfile.IndexOf(target_string) <> -1 Then
MsgBox(TextBox1.Text & " was found ")

Else
MsgBox(TextBox1.Text & " was NOT found ")


End If

I just want to take out example.txt and insert an *.txt, which in python would translate into a wild card. I was told about using Directory.GetFiles to get a list of files within a directory and then loop it until all files are read in that directory. I have no idea how to do that and the person didn't really explain much other than give me that piece of information. I only know so much about VB since I took a course in high school on the basics and my college didn't bring VB up in any courses. If there is any additional resources I could use for VB knowledge feel free to post them here. Thanks


Re: How to search multiple files for one string - brandonio21 - 06-18-2012

I believe something like this may solve your problem!

Code:
Public Function GetFilesContaining(ByVal key As String, ByVal directoryPath As String) As List(Of System.IO.FileInfo)
        Dim filesContaining As New List(Of System.IO.FileInfo) 'This will store what files contain the keyword
        Dim directoryInfo As New System.IO.DirectoryInfo(directoryPath)
        Dim filesInDirectory() As System.IO.FileInfo = directoryInfo.GetFiles("*.txt", True)
        'Now, scroll through all the files and see if it contains a value
        For Each file As System.IO.FileInfo In filesInDirectory
            If (IO.File.ReadAllText(file.FullName).Contains(key)) Then 'The file contains the key
                filesContaining.Add(file) 'Add it to the return list
            End If
        Next

        'Return the list
        Return filesContaining
    End Function

As far as VB.NET help goes, feel free to experiment! Have a goal in mind, and try to accomplish it on your own. That's the best way to learn.