Other Stream Classes

BufferedStream improves read and write performance by caching data in memory and reducing the number of calls that need to be made to the operating system. BufferedStream isn't used on its own, but instead is wrapped around certain other types of streams, in particular, the BinaryWriter and BinaryReader classes described as follows.

The BinaryWriter and BinaryReader classes are used to read and write primitive data types rather than raw bytes. In reality, these classes convert between primitive types and raw bytes, so they need to work with a basic Stream object—such as FileStream or MemoryStream—that handles the I/O of the bytes. The BaseStream property of both of these classes lets you get a reference to the underlying Stream object. Table 6.7 lists the methods of the BinaryWriter class.

Table 6.7: 1 ili ta|li dss

Method

Description

Close

Closes the BinaryWriter and releases any resources associated with it.

Flush

Causes any unwritten data that remains in the BinaryWriters buffers to be written.

Seek

Moves the seek pointer.

Write

Writes a value to the stream. See the following details of this method.

Write7BitEncodedInt

Writes a 32-bit integer in a compressed format.

The Write() method has no fewer than 18 overloads that handle writing .NET basic types, such as:

■ The integer types (Int16, Int32, Int64, and their unsigned equivalents)

■ Bytes and arrays of bytes

■ Single and double floating-point numbers

■ Char and arrays of Char

The BinaryReader has very nearly the same functionality, but the reading methods are not overloads of one function. For example, in BinaryWriter, you have Write(Int16) and Write(Char), whereas in BinaryReader, you have ReadInt16() and ReadChar(). The reason is clear when you think about it: when writing, the writer object can deduce what it has to write from the type of the argument to Write(). When reading, faced with a stream of bytes, the reader does not know how it is supposed to put them together. You need to tell the reader how to put the stream of bytes together by calling a particular function. See the Immediate Solutions section for an example of using these classes to perform binary I/O.

And, finally, although it isn't part of the System.IO namespace, the System.Net.Sockets.NetworkStream class lets you perform stream-based I/O using network sockets.

0 0

Post a comment