Reading .txt file
I am using following code to开发者_如何转开发 read text from a .txt file. But I don't know how to perform search within file and how to read a specific line in the text file, based on search.
Dim vrDisplay = My.Computer.FileSystem.ReadAllText(CurDir() & "\keys.txt")
MsgBox(vrDisplay)
For an example,
if I want to read the line that contains the word "Start", how to do that
Thanks.
Instead of reading all text, for efficiency's sake,
- Open a FileStream for the file in question.
- Create a StreamReader.
- Loop through, calling ReadLine until either you find the end of the file, or the string contains "Start".
Edit: even if it's required that you keep the entire file in memory, you can still do the above by using a MemoryStream()
.
It isn't easy to tell from your post if it's the best possible solution, but one solution would be to use regular expressions to find all lines containing the word Start
:
^.*\bStart\b.*$
matches an entire line that contains the complete word Start
anywhere. It rejects Start
as a part of a word, for example Starting
won't be matched (that's what the \b
word boundary anchors are for).
To use this in VB.NET:
Dim RegexObj As New Regex(
"^ # Start of line" & chr(10) & _
".* # Any number of characters (anything except newlines)" & chr(10) & _
"\b # Word boundary" & chr(10) & _
"Start # ""Start""" & chr(10) & _
"\b # Word boundary" & chr(10) & _
".* # Any number of characters (anything except newlines)" & chr(10) & _
"$ # End of line",
RegexOptions.Multiline Or RegexOptions.IgnorePatternWhitespace)
AllMatchResults = RegexObj.Matches(vrDisplay)
If AllMatchResults.Count > 0 Then
' Access individual matches using AllMatchResults.Item[]
Else
' Match attempt failed
End If
精彩评论