Reading a Text File Line by Line

Ciduletz1983

Active member
Joined
Oct 10, 2006
Messages
30
Location
Constanta, Romania
Programming Experience
Beginner
Good day. I learn VB.NET alone. No support. Just some dumb tutorials. I can`t understand the meaning of "peek" and " -1 " in this code:

VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim FILE_NAME As String = "C:\test.txt"
        Dim TextLine As String

        If System.IO.File.Exists(FILE_NAME) = True Then

            Dim objReader As New System.IO.StreamReader(FILE_NAME)

            Do While objReader.Peek() <> -1
                TextLine = TextLine & objReader.ReadLine() & vbNewLine
            Loop

            TextBox1.Text = TextLine

        Else

            MsgBox("File Does Not Exist")

        End If
    End Sub

Could someone here explain me ? Please!
 
This is the easiest solution:

VB.NET:
[SIZE=2][COLOR=#0000ff]Private [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE][SIZE=2] Button2_Click([/SIZE][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] sender [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] System.Object, [/SIZE][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] e [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] System.EventArgs) [/SIZE][SIZE=2][COLOR=#0000ff]Handles[/COLOR][/SIZE][SIZE=2] Button2.Click[/SIZE]
[SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][SIZE=2] objReader [/SIZE][SIZE=2][COLOR=#0000ff]Is [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Nothing [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Then [/COLOR][/SIZE][SIZE=2][COLOR=#008000]'objReader has not been set yet[/COLOR][/SIZE]
[SIZE=2]   Button1.PerformClick() [COLOR=#008000]'executes Button1_Click where the objReader is initiated[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]End [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][SIZE=2] objReader.Peek() <> -1 [/SIZE][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE]
[SIZE=2]   TextBox1.Text = objReader.ReadLine()[/SIZE]
[SIZE=2][COLOR=#0000ff]End [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]End [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Sub[/COLOR][/SIZE]
 
Back
Top