Thursday, 12 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
  List1.AddItem someStrings(x)
 Next x

End Sub


First we get a file handle to the file we want to open. We declare an integer and use the FreeFile method to get a filehandle. We then use the Open function to open a file and assign the file handle. Note the use of the pound sign (#) here. We also declare a large string array, which is one dimensional. We use the ReDim Preserve Method to resize the array to save some memory space and preserve the content. We use the Input Method to put each line into an array element before this is done. Note the use of EOF here. We finally loop through the array and add each array item to a listbox control. So now you should have some basic overview how you can read a file in VB6 into an array structure and loop through its content. How neat is that!
Share this article on LinkedIn.

2 comments: