CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
userData.WindowColor = "Yellow";
userData.FontSize = 50;
// The BinaryFormatter persists state data in a binary format.
// You would need to import System.Runtime.Serialization.Formatters.Binary
// to gain access to BinaryFormatter.
BinaryFormatter binFormat = new BinaryFormatter();
}
// Store object in a local file.
using(Stream fStream = new FileStream("user.dat",
FileMode.Create, FileAccess.Write, FileShare.None))
{
binFormat.Serialize(fStream, userData);
}
Console.ReadLine();
.NET object serialization makes it easy to persist objects; however, the processes used behind the
scenes are quite sophisticated. For example, when an object is persisted to a stream, all associated data
(e.g., base class data and contained objects) are automatically serialized, as well. Therefore, if you
attempt to persist a derived class, all data up the chain of inheritance comes along for the ride. As you
will see, you use an object graph to represent a set of interrelated objects.
.NET serialization services also allow you to persist an object graph in a variety of formats. The
previous code example uses the BinaryFormatter type; therefore, the state of the UserPrefs object is
persisted as a compact binary format. You can also persist an object graph into SOAP or XML format
using other types. These formats can be quite helpful when you need to ensure that your persisted
objects travel well across operating systems, languages, and architectures.
Note WCF prefers a slightly different mechanism for serializing objects to/from WCF service operations; it uses
the [DataContract] and [DataMember] attributes. You’ll learn more about this in Chapter 25.
Finally, understand that you can persist an object graph into any System.IO.Stream-derived type. In
the previous example, you used the FileStream type to persist a UserPrefs object into a local file.
However, if you would rather store an object to a specific region of memory, you could use a
MemoryStream type instead. All that matters is the fact that the sequence of data correctly represen