STREAMREADER AND STREAMWRITER

The StreamReader and StreamWriter classes let a program read and write data in a stream. The underlying stream is usually a FileStream. You can pass a FileStream into these classes’ constructors, or you can pass a filename and the object will create a FileStream automatically.

The StreamReader provides methods for reading lines, characters, or blocks of characters from the stream. Its ReadToEnd method returns any of the stream that has not already been read. The EndOfStream method returns True when the StreamReader has reached the end of the stream.

Example program ReadLines uses the following code fragment to read the lines from a file and add them to a ListBox control:

' Open the file.
Dim stream_reader As New StreamReader("Animals.txt")
 
' Read until we reach the end of the file.
Do Until stream_reader.EndOfStream()
    lstValues.Items.Add(stream_reader.ReadLine())
Loop
 
' Close the file.
stream_reader.Close()

The StreamWriter class provides methods to write text into the stream with or without a new-line character.

StreamReader and StreamWriter are derived from the TextReader and TextWriter classes and inherit the definitions of most of their properties and methods from those classes. See the section “TextReader and TextWriter” earlier in this chapter for a description of these properties and methods.

The StreamWriter class adds a new AutoFlush property that determines whether the writer flushes its buffer after every write.

Example program StreamWriterReader ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.