Like the legacy Input function above, Stream supports reading and writing bytes. But it does so much more! A stream could also be data "streaming" in from a network port or a piece of lab equipment. Streaming to a file is just a good introduction to a much larger and more useful technology, but let's see how that works.
Imports System.IO
FileName = "Win.Ini"
Using s As StreamReader = New StreamReader(FileName)
Dim line As String
Do
line = s.ReadLine()
Console.WriteLine(s.ReadLine())
Loop Until line Is Nothing
s.Close()
End Using
The example shows that the familiar ReadLine method is available, but you can also read blocks, entire files, or just Peek at the next character without "consuming" it. Using a StreamReader to read a simple sequential file is a little like driving to the corner store in a 50 ton truck. But it works.
TextFieldParser - A Better CSV
Earlier, I wrote that a better way to read CSV files would be demonstrated. TextFieldParser in Microsoft.VisualBasic.FileIO is the better way. This code (adapted from Microsoft) includes a Using block to declare a new TextFieldParser object. The Using block makes certain that the object is destroyed again when it's not needed at the end. It also checks for problems using a Try-Catch block. But the essential function is that it reads the same CSV file that we saw earlier.
FileName = "CSVFile.txt"
Using CSVReader As New _
TextFieldParser(FileName)
CSVReader.TextFieldType = _
FileIO.FieldType.Delimited
CSVReader.SetDelimiters(",")
Dim currentRow As String()
While Not CSVReader.EndOfData
Try
currentRow = CSVReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
Console.WriteLine(currentField)
Next
Catch ex As _
MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using
If your file has a different delimiter, just tell TextFieldParser what it is. This line of code allows a file delimited with tab characters to be read.
TabReader.Delimiters = New String() {vbTab}

