How to get the entire line of text containing a string

advertisements

There's one thing that I want to ask. How can I get the whole line of text that contain a string in Visual Basic 2010?

Let's say:

MyText.txt file contains:

Configurations:
Name: Fariz Luqman
Age: 78
My Favourite Fruit: Lemon, Apple, Banana
My IPv4 Address: 10.6.0.5
My Car: Ferrari

In Visual Basic, I want to get the whole line of text that contain the string "Banana" and print it in the textbox so it will display in that textbox:

My Favourite Fruit: Lemon, Apple, Banana

Why am I doing this? Because the text file is being appended and the line number is random. The contents is also random because the texts is generated by Visual Basic. The text "Banana" can be in line 1, line 2 or can be in any line so how can I get the whole line of text that contain certain string?

Thank you in advance!


You can do this easily all in one line with LINQ:

TextBox1.Text = File.ReadAllLines("MyText.txt").FirstOrDefault(Function(x) x.Contains("Banana"))

However, if the file is rather large, that's not particularly efficient, since it will read the whole file into memory before searching for the line. If you want to make it stop loading the file once it finds the line, could use the StreamReader, like this:

Using reader As New StreamReader("Test.txt")
    While Not reader.EndOfStream
        Dim line As String = reader.ReadLine()
        If line.Contains("Banana") Then
            TextBox1.Text = line
            Exit While
        End If
    End While
End Using