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(","))) aCollection.Add(anArray) strRecord = aStreamReader.ReadLine Loop aFileStream.Close() aStreamReader.Close()
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:
System.IO.File.Delete("TestFile.txt") 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, ",") aStreamWriter.WriteLine(strLineText) Next aStreamWriter.Close() aFileStream.Close()
Always make sure you close the streams. Closing the FileStream releases the lock on the file.
This was first published in July 2004