I have a sub to read a text file and search it for a specific piece of text so that it will match any search term found (test, test2, test3 or test4). The idea is that if test is found then the line of text following it will be displayed, the same for test2 and so on.
However if no match is found it gives an error about a Null pointer exception for this line of the sub....
If line.CompareTo(searchterm) = 0 Then found = True
Yet I get the same error if I type in the word test, the first keyword and first line of the text file. In other words if no match is found, or if I search for the first item in the text file I get this error and don't know why. Any ideas, please?
The test file is a plain text file that just contains what is within the quote marks below (not the quotes themselves):
"test
data for test
test2
data for test2
test3
yes its test3
test4
yes it is test4"
And the sub that searches is:
Sub dosearch
Reader.Initialize(File.OpenInput(File.DirAssets, "test.txt"))
line = Reader.ReadLine
found = False
Do While line <> Null
line = Reader.ReadLine
If line.CompareTo(searchterm) = 0 Then found = True
If found = True Then Exit
Loop
If found = False Then Msgbox("Didn't find ingredient", "Error:")
If Found = True Then
ingredient = line
line = Reader.ReadLine
description = line
Reader.Close
Msgbox(ingredient,description)
End If
End Sub
Where ingredient, description and line are strings and searchterm is a string that holds the text to find a match for, previously entered by the user.
I know that I can make this work if I read the file in as a list, so if I cannot find the answer I can adapt my code, but I would rather know why this code will never find the first line of text and why it crashes if no data is matched so I can learn from my apparent mistake so any advice is appreciated
Dave