Read a file line by line using VB6

Visual Basic Topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Read a file line by line using VB6

Post by Neo » Tue Apr 05, 2011 3:18 pm

Here is the code to read a file and list contents in a text box.
Make sure you add a Button (Command1) and a TextBox (Text1) to the project. Set MultiLine = True under TextBox properties. Also, place a file with few lines named myfile.txt under C:\.

Code: Select all

Option Explicit

Dim FileNum As Integer, strText As String, strLine As String, LineCount As Long



Private Sub Command1_Click()
    
    ' Get a free file number
    FileNum = FreeFile
    
    ' Open a text file for input. inputbox returns the path to read the file
    Open "C:\myfile.txt" For Input As FileNum
    LineCount = 1
    
    ' Read the contents of the file
    Do While Not EOF(FileNum)
    
        ' Read line
        Line Input #FileNum, strLine
        
        ' Add line text to main text with line breaks
        strText = strText & strLine & vbCrLf
        
        LineCount = LineCount + 1
    Loop
    
    Text1.Text = strText
    
    ' Close the file
    Close FileNum

End Sub
Post Reply

Return to “Visual Basic Programming”