Hi Ari,
You can easily use Regular Expressions to do this, too. I'm not sure,
but it may be more efficient than reading 1 character at a time.The
Following
example searches for the text "the more you forget" in a text file called
"Logic.txt",
containing the following 4 lines :
=============================
The more you learn, the more you know,
The more you know, the more you forget,
The more you forget, the less you know
So.. why learn.
=============================
It then outputs just the Line which contained the text you needed to search
for.
The sample code is :
---------------------------------
'Get the contents of the text file in a String variable.
Dim fs As New FileStream("..\Logic.txt", FileMode.Open, FileAccess.Read)
Dim sr As New StreamReader(fs)
Dim Contents As String = sr.ReadToEnd()
' Store the string you want to search for using a Regular expression. The
caret indicates the start of the line.
' (.*?) can match any text. Each set of enclosing brackets indicates 1 group
within the matched line.
Dim strSearch As String = "^(.*?)(the more you know,)"
' Create a Regex Object with this Regular expression. It is essential to set
the option "Multiline" in this case,
' which will give the intended meaning to the Caret.
Dim myRegex As New Regex(strSearch, RegexOptions.Multiline)
If myRegex.IsMatch(Contents) Then
'The match succeeded. Get the matched text. The whole Match instance is
equivalent to Match.Groups(0).
Dim myMatch As Match = myRegex.Match(Contents)
Dim theFoundLine As String = myMatch.Groups(0).Value
'Display the found line
MsgBox(theFoundLine)
'Optionally get the Length of the match and it's position in the input
string.
MsgBox(myMatch.Length)
MsgBox(myMatch.Index)
Else
MsgBox("Failed")
End If
---------------------------------
Hope that should help.
Chris wrote :
Do while FileStream.Peek <> -1
Dim Line as sTring = FileStream.Readline
if Line.Indexof(StringToFind) <> -1 then exit loop
Loop
You probably made a few typos, Chris. The Peek method is only available to
the StreamReader class, not the FileStream class, as is the ReadLine method.
Finally, it's Exit Do and not Exit Loop ;-)
Warm Regards,
Cerebrus.