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 class’s constructors, or you can pass a file name 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 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.

The following simple example shows how to use a StreamReader and StreamWriter. It generates a file name and passes it into a StreamWriter class’s constructor. It uses the StreamWriter class’s Write and WriteLine methods to place two lines of text in the file. It then closes the file. If you were to open the file now with a text editor, you would see the text. The program then creates a new StreamReader, passing its constructor the same file name. It uses the reader’s ReadToEnd method to grab the file’s contents and displays the results.

  Dim file_name As String = Application.StartupPath & "\test.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 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.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net