Wednesday, 11 November 2015

Reading a text file in VB6 and putting the contents into an array

VB6 or Visual Basic 6.0 is not used in many new projects, as it is replaced by .NET. But sometimes you are assigned at work to read and further develop or migrate Legacy code. Let's look at some simple VB6 code. We first read the contents of a file and put each line into a string array. Then we add the items to a listbox control.

Private Sub Command3_Click()

Dim someFileHandle As Integer
Dim fileName As String
Dim someStrings() As String

someFileHandle = FreeFile

fileName = App.Path + "\fox.txt"

ReDim someStrings(1000) As String

Open fileName For Input As #someFileHandle

Dim lineNo As Integer

Do Until EOF(someFileHandle)
Input #someFileHandle, someStrings(lineNo)
lineNo = lineNo + 1
Loop

ReDim Preserve someStrings(lineNo - 1) As String

List1.Clear

For x = 0 To lineNo - 1