How to read a specific line from a text file in VB

I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.

Here is my code:

Public Class Form1

    Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
         Dim writer As New System.IO.StreamWriter("/text.txt", True)
         writer.WriteLine(txtFirstName.Text)
         writer.WriteLine(txtLastName.Text)
         writer.WriteLine("-------------------------------------")
         writer.Close()
    End Sub

     Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
        Dim reader As New System.IO.StreamReader("/text.txt")
        Dim FirstName, LastName As String
        FirstName = reader.ReadLine()
        LastName = reader.ReadLine()
        reader.Close()
        txtFirstName.Text = FirstName
        txtLastName.Text = LastName
    End Sub

    Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
        txtFirstName.Clear()
        txtLastName.Clear()
    End Sub
End Class

Any help would be appreciated. Thanks!


Solution 1:

You will have to read all lines up to the one you're interested in. For example:

Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
    Using file As New StreamReader(filePath)
        ' Skip all preceding lines: '
        For i As Integer = 1 To lineNumber - 1
            If file.ReadLine() Is Nothing Then
                Throw New ArgumentOutOfRangeException("lineNumber")
            End If
        Next
        ' Attempt to read the line you're interested in: '
        Dim line As String = file.ReadLine()
        If line Is Nothing Then
            Throw New ArgumentOutOfRangeException("lineNumber")
        End If
        ' Succeded!
        Return line 
    End Using
End Function

This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.

If you frequently need to load a specific line, you have some more options:

  • Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.

  • Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.

Solution 2:

Try this:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim reader As New System.IO.StreamReader("C:\text.txt")
    Dim allLines As List(Of String) = New List(Of String)
    Do While Not reader.EndOfStream
        allLines.Add(reader.ReadLine())
    Loop
    reader.Close()
    txtFirstName.Text = ReadLine(5, allLines)
    txtLastName.Text = ReadLine(6, allLines)

End Sub

Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
    Return lines(lineNumber - 1)
End Function

If you had a file with this:

Line 1
Line 2
Line 3
Line 4
My Name
My LastName

your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.

Solution 3:

This is very simple, try this:

Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3

myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString