CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Binary Writers / Readers *****\n");
// Open a binary writer for a file.
FileInfo f = new FileInfo("BinFile.dat");
using(BinaryWriter bw = new BinaryWriter(f.OpenWrite()))
{
// Print out the type of BaseStream.
// (System.IO.FileStream in this case).
Console.WriteLine("Base stream is: {0}", bw.BaseStream);
// Create some data to save in the file.
double aDouble = 1234.67;
int anInt = 34567;
string aString = "A, B, C";
// Write the data.
bw.Write(aDouble);
bw.Write(anInt);
bw.Write(aString);
}
}
Console.WriteLine("Done!");
Console.ReadLine();
Notice how the FileStream object returned from FileInfo.OpenWrite() is passed to the constructor
of the BinaryWriter type. Using this technique makes it easy to layer in a stream before writing out the
data. Note that the constructor of BinaryWriter takes any Stream-derived type (e.g., FileStream,
MemoryStream, or BufferedStream). Thus, writing binary data to memory instead is as simple as supplying
a valid MemoryStream object.
To read the data out of the BinFile.dat file, the BinaryReader type provides a number of options.
Here, you call various read-centric members to pluck each chunk of data from the file stream:
static void Main(string[] args)
{
...
FileInfo f = new FileInfo("BinFile.dat");
...
// Read the binary data from the stream.
using(BinaryReader br = new BinaryReader(f.OpenRead()))
{
Console.WriteLine(br.ReadDouble());
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadString());
}
Console.ReadLine();
}
777