Reading from a text file

Reading a textfile is pretty straight-forward in VB6.

Opening the file

First of all, you need to open the file. It's always a good idea to provide a full pathname (e.g. C:\My Folder\My Data\myFile.txt instead of just myFile.txt).

You need to give the file a file number so that you can refer to it later on. In the example below I've given mine the designation of file number 1 - by using #1.

Note the word Input - denoting that you will be using the file for input.

Open App.Path & "\data.txt" For Input As #1

Reading from the file

To read from the file you just use the command Input Line <file number>, <string variable>. This will read one line of text from the file and store it in the string variable. If my variable was called strReadFile and the file was #1 then I would use the command:

Input Line #1, strReadFile

Checking if you've reached the end

It's important that before you try to read from the file you check if you've reached the end of the file. This is easy to do. The function EOF(<file number>) will return true or false depending on whether the end of the file has been reached (EOF = End of File). Look at the example code at the end to see EOF in use.

Closing the file

It's important that you remember to close the file when you've finished reading from it, otherwise you might not be able to re-open the file later in your program. All you need to do is use the keyword Close, followed by the file number.

Close #1

Putting it all together

The Visual Basic code below opens a textfile called "test.txt" in the same folder as the project when the program is run. If you try to use this you will need to create the text file yourself. After opening the file it will read each line of the file until it reaches the end and pop up a message box displaying the line. Because this could be really annoying you might not want to put many lines in your text file.


VB6 Example

Private Sub Form_Load()

    ' This sub is triggered when the program first runs and
    ' the form is loaded
   
    ' Create a string variable called strFileLine
    Dim strFileLine As String
   
    ' Clear the list before loading the data
    lstItems.Clear
   
    ' Open the text file for input
    Open App.Path & "\test.txt" For Input As #1
   
    ' Loop as long as the end of the file hasn't been reached
    While Not EOF(1)
 
        ' Get a line of input from the file and
' store it in the variable called strFileLine
        Line Input #1, strFileLine
 
        ' Display the string (strFileLine) in a message box
        MsgBox strFileLine
    Wend
   
    ' Close the file
    Close #1
   
End Sub