Question How to read certain lines in a text file?

Haxaro

Well-known member
Joined
Mar 13, 2009
Messages
105
Programming Experience
1-3
I want to make a program that reads the line of a file, and puts it into a text box, then reads the second line in that file, putting it in another text box... Say i only have a file with two lines, how can i do this?

I have written a code, but it only works for the first line. Is there a preset function in Visual Basic that will allow me to read a certain line?

VB.NET:
Imports System.IO.StreamReader
VB.NET:
Dim AllText As String = vbNull, Lineoftext As String = vbNull
        Dim Open_File As New OpenFileDialog    ' Dim Open_File as a Open File Dialog
        Dim A
        Open_File.ShowDialog()                  ' Open the Open File Dialog
        A = Open_File.FileName                  ' A = The path of the dialog

        Dim objReader As New StreamReader(Open_File.FileName)

        Dim TextLine As String = vbNull

        TextLine = objReader.ReadLine()
            If objReader.Peek = -1 Then
                Exit Sub
            End If


        LineNumber1.Text = TextLine

I could just do it once, and loop it, using i + 1 or something... (i being the line number)

so i am wondering if there is a function that will allow me to:

VB.NET:
Open File "FILE NAME"
Do until i = EOF
FileName.ReadLine(i = i + 1)
Loop

Thanks
 
Why don't you read your file into an array? Then you can access any line at will when you need it.

VB.NET:
Dim lines() As String = IO.File.ReadAllLines(path)
Dim line2 As String = lines(1)

If you're wanting to loop through the file:

VB.NET:
Do While objReader.Peek <> -1
     currentLine = objReader.ReadLine()
     ...
 
Back
Top