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

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.

Leave a Comment