MadsTheMan MadsTheMan - 6 months ago 12
Vb.net Question

How can I look for certain words in a file and then do something?

How can I look for certain words in a file then do something if any of the words were found?

I would like to do something if for example any of these words

banana
horse
window
whatever
is found within a file.

Here is my last attempt

Dim thefile As String = "C:\application\thefile"

If File.Exists(thefile) Then
Using reader As New StreamReader(thefile)
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()

If line.Contains("Banana") OrElse line.Contains("horse") OrElse line.Contains("window") OrElse line.Contains("whatever") Then
msgbox("Word(s) found " & line)
Do_this_and_that()
Else
MsgBox("Word(s) not found")


Exit While
End If
End While
End Using
Else
msgbox("File not found")
End If


There seem to be so many variations of doing this, but I can't get them to work when its multiple words instead of just one. What is the easies and cleanest way of doing this?

Answer

This might be a bit of a performance issue, but you can try using a List(Of String) :

Dim thefile As String = "C:\application\thefile"
Dim toCheck as New List(of String)
'You can fill up your list by whoever you want
toCheck.Add("banana")
toCheck.Add("horse")
'...
Dim FoundWords As New List(Of String)

If File.Exists(thefile) Then
    Using reader As New StreamReader(thefile)
        While Not reader.EndOfStream
            Dim line As String = reader.ReadLine()

            'We check our list to see if it matches
            For Each item in toCheck
                if line.Contains(item) then
                    FoundWords.Add(item)
                End If
            Next
        End While
    End Using

    If FoundWords.Count > 0 Then
        msgbox(FoundWords.Count.ToString() & " Word(s) found")
        Do_this_and_that()    
    Else
        MsgBox("Word(s) not found")    
    End If
Else
    msgbox("File not found")
End If

Now this can be improved but if you don't have thousand of words to look for that should do the trick...