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 uses the following code to demonstrate the StreamReader and StreamWriter classes:

Dim file_name As String = Application.StartupPath & "	est.txt"
Using stream_writer As New StreamWriter(file_name)
    stream_writer.Write("The quick brown fox")
    stream_writer.WriteLine(" jumps over the lazy dog.")
    stream_writer.Close()
End Using
 
Using stream_reader As New StreamReader(file_name)
    MessageBox.Show(stream_reader.ReadToEnd())
    stream_reader.Close()
End Using

This code generates a filename and passes it into a StreamWriter class’s constructor. It uses the StreamWriter class’s Write and WriteLine methods to place two pieces of text in the file and then closes the file. If you were to open the file at this point with a text editor, you would see the text.

The program then creates a new StreamReader, passing its constructor the same filename. It uses the reader’s ReadToEnd method to grab the file’s contents and displays the results.

This example would have been much more awkward using a FileStream object’s lower-level Write and Read methods to manipulate byte arrays. Compare this code to the example in the “FileStream” section earlier in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.102.142