CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
}
Console.ReadLine();
}
This example populates the file with data, but it also punctuates the major downfall of working
directly with the FileStream type: it demands to operate on raw bytes. Other Stream-derived types
operate in a similar manner. For example, if you want to write a sequence of bytes to a region of
memory, you can allocate a MemoryStream. Likewise, if you want to push an array of bytes through a
network connection, you can use the NetworkStream class (in the System.Net.Sockets namespace).
As mentioned previously, the System.IO namespace provides several reader and writer types that
encapsulate the details of working with Stream-derived types.
Source Code You can find the FileStreamApp project is under the Chapter 20 subdirectory.
Working with StreamWriters and StreamReaders
The StreamWriter and StreamReader classes are useful whenever you need to read or write characterbased data (e.g., strings). Both of these types work by default with Unicode characters; however, you can
change this by supplying a properly configured System.Text.Encoding object reference. To keep things
simple, assume that the default Unicode encoding fits the bill.
StreamReader derives from an abstract type named TextReader, as does the related StringReader
type (discussed later in this chapter). The TextReader base class provides a limited set of functionality to
each of these descendants; specifically it provides the ability to read and peek into a character stream.
The StreamWriter type (as well as StringWriter, which you will examine later in this chapter) derives
from an abstract base class named TextWriter. This class defines members that allow derived types to
write textual data to a given character stream.
To aid in your understanding of the core writing capabilities of the StreamWriter and StringWriter
classes, Table 20-8 describes the core members of the abstract TextWriter base class.
Table 20-8. Core Members of TextWriter
Member
Meaning in Life
Close()
This method closes the writer and frees any associated resources. In the process,
the buffer is automatically flushed (again, this member is functionally equivalent to
calling the Dispose() method).
Flush()
This method clears all buffers for the current writer and causes any buffered data to
be written to the underlying device; however, it does not close the writer.
NewLine
This property indicates the newline constant for the derived writer class. The
default line terminator for the Windows OS is a carriage return, followed by a line
feed (\r\n).
Write()
This overloaded method writes data to the text stream without a newline constant.
WriteLine()
This overloaded method writes data to the text stream with a newline constant.
771