About   -   Contact   -   Purchase   -   Search   -   What's New

Opening ASCII files
The choice of methods for retrieving data from flat ASCII files in VB is fairly extensive and ranges from simple to not so simple in complexity. For starters there's:
  • ADO
  • File System Object
  • GetPrivateProfileString API
  • Open file I/O

That said, the simplest and most reliable method is the open statement used to enable output from or input to a file. The only exception to this is file handling used in conjunction with INI file when [square brackets] are used to organise to INI file structure.

The following subroutine demonstates how to open and read from a file:

Sub ReadFile(TextFileName As String)
Dim strOneLine As String
Dim intNum As Integer

    intNum = FreeFile
    Open TextFileName For Input As intNum

    Do While Not EOF(intNum )
	' Read a line at a time
	Line Input #intNum, strOneLine

 	'each line held as string strOneLine

    Close intNum

End Sub

The FreeFile object creates a unique identifier that correspond to the file you've specified in the TextFileName argument of the subroutine. This becomes useful to distinguish two files, if one is opened one for reading and the other for writing. The TextFileName argument should hold the full path of the text file, e.g. "c:\temp\test.txt". Once the file has been opened then its contents are read in a line at a time using the Line Input command. 

Alternatively, the Input command can be used to read in data from the file, one item at a time, as shown in the modified loop below:

    Do While Not EOF(intNum )
	' Read a line at a time
	Input #intNum, strOneLine

 	'each item held as string strOneLine

If the data is comma delimited then the Input statement will return the contents of the file between the start of the line and the first comma, between commas or between the last comma and the next line break. Otherwise if commas have not been used then the entire line will be returned as with the Line Input statement.


Top of Page

Legal Notice

Ken Howe 2011