Encapsulating Raw Streams
While the Stream class reads and writes raw bytes,
most programs prefer to produce and consume data either in the form of native
data types or lines of text. To make this easy, the framework includes related
pairs of XXXReader/XXXWriter classes
that provide this higher-level, encapsulated access to the raw underlying
data stream.
The BinaryReader and BinaryWriter Classes
BinaryReader and BinaryWriter are
concrete classes that define operations for reading and writing a stream of
native data types. The most fundamental operations of the BinaryReader and BinaryWriter classes
are the methods that read and write instances of the primitive data types: bool, byte, char, decimal, float, double, short, int, long, sbyte, ushort, uint, and ulong.
Additionally, methods are provided to read and write strings
and arrays of the primitive data types.
Imagine we have a simple class, defined as follows, that we want to read and write from a stream:
public class Student {
public string Name;
public int Age;
public double GPA;
}Methods that read and write instances of the Student class
from a stream in a binary format might look like this:
void SaveToStream(Stream stm, Student s) { BinaryWriter bw = new BinaryWriter(stm); bw.Write(s.Name); bw.Write(s.Age); bw.Write(s.GPA); bw.Flush(); // Ensure the BinaryWriter buffer is empty } void ReadFromStream(Stream stm, Student s) { BinaryReader br = new BinaryReader(stm); s.Name = br.ReadString(); s.Age = br.ReadInt32(); s.GPA = br.ReadDouble(); ...