Reading in lines from text file

tahu191

Well-known member
Joined
Oct 27, 2005
Messages
48
Location
USA
Programming Experience
Beginner
I need to know how to read a specific line from a text file, such as read line 1 or read line 37 or line 77. Thanks I very much appreciate this.
 
You read a text file sequentially so you would have to read every line up to and including the one you were interested in:
VB.NET:
        Dim myStreamReader As New IO.StringReader(filePath)
        Dim line As String
        Dim currentLineNumber As Integer = 0

        Do
            line = myStreamReader.ReadLine()
            currentLineNumber += 1
        Loop Until currentLineNumber = desiredLineNumber
 
The other alternative would be to read the entire file and then pick out the line you wanted:
VB.NET:
        Dim myStreamReader As New IO.StringReader(filePath)
        Dim fileContents As String = myStreamReader.ReadToEnd()
        Dim lines As String() = System.Text.RegularExpressions.Regex.Split(fileContents, Environment.NewLine)
        Dim line As String = lines(desiredLineNumber)
 
Back
Top