D.Ch
D.Ch

Reputation: 11

Read certain line in text file and display the next

I am new to VB.net and I need help. What I am trying to do is to find a certain line in a text file and display the next line in a textbox. With the first part (finding the line) I'm doing just fine but I am struggling with the second part which is displaying the line that is after the one I have found!

Here is the content of the test file that I am using:

**SCREENSHOT OF THE TEXT FILE**

lol

And this is what I have done so far:

    Using sReader As New StreamReader("filepath")

        While Not sReader.EndOfStream
            Dim line As String = sReader.ReadLine()
            If line.Contains("123") Then
                TextBox1.Text = line
            End If
        End While

    End Using

Received result:

**HERE IS A SCREENSHOT OF MY OUTPUT**

Upvotes: 0

Views: 1299

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460158

While Not sReader.EndOfStream
    Dim line As String = sReader.ReadLine()
    If line.Contains("123") AndAlso Not sReader.EndOfStream Then
        Dim nextLine As String = sReader.ReadLine()
        TextBox1.Text = nextLine
        Exit While
    End If
End While

With LINQ the complete code can be made much more readable:

Dim nextLineAfterMatch = File.ReadLines("filepath").
    SkipWhile(Function(line) Not line.Contains("123")).
    Skip(1).
    FirstOrDefault()

If nextLineAfterMatch IsNot Nothing Then TextBox1.Text = nextLineAfterMatch 

Upvotes: 2

Related Questions