Accessing QB files with VB.NET

I have to access files that were created using QB. The files consist of ASCII text, integers, floating point numbers

and the like separated by commas. In QB, I used something like: OPEN filename FOR RANDOM AS #1. Then I would write using WRITE #1, data1, data2, data3 and so on. I'm not sure of the exact syntax since it's been so long, but I need to do the same thing with VB.NET. Is there a simple method for this? Everything I've read so far has to do with saving a lot of plain text or using databases. Thanks! I suspect what you are doing is Data Transformation for Comma Delimited ASCII. I also suspect there is some kind of record terminator between the records since they will be of variable length.

VB.NET provides a FileStream class to which you can pass the file name and the type of open you want to use. Then you can wrap the FileStream with a StreamReader and use the ReadLine method to read the file one line at a time into a String variable. With one line of code you can "Split" the incoming record into elements of a string array with the Split method of the String object or you can invoke the Split function. At this point you have the fields from the incoming record separated into the elements of a string array.

To read the records and break out the columns you can use something like this to read and accumulate values into a collection from a file containing a string, an integer, a decimal, and a date:

Dim aCollection As New Collection
Dim aFileStream As New System.IO.FileStream("TestFile.txt", IO.FileMode.Open)
Dim aStreamReader As New System.IO.StreamReader(aFileStream)
Dim strRecord As String
strRecord = aStreamReader.ReadLine
Do Until strRecord Is Nothing
 Dim anArray As String() = strRecord.Split(Chr(Asc(",")))
 strRecord = aStreamReader.ReadLine

Writing data back to the disk is just the opposite. Use the FileStream to connect to the disk datafile. Wrap the FileStream in a StreamWriter and use the WriteLine method to write each line of data. "Join" the elements of a string array into a single string field with the Join function.

Then you can write the same data back to a disk file with the following:

Dim aFileStream As New System.IO.FileStream("TestFile.txt", IO.FileMode.OpenOrCreate)
Dim aStreamWriter As New System.IO.StreamWriter(aFileStream)
Dim strArray As String()
For Each strArray In aCollection
 Dim strLineText As String = Join(strArray, ",")

Always make sure you close the streams. Closing the FileStream releases the lock on the file.

This was first published in July 2004

Dig deeper on Win Development Resources

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.



Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: