Free mag vol1 | Page 841

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION If you want to persist an object’s state in a manner that can be used by any operating system (e.g., Windows, Mac OS X, and various Linux distributions), application framework (e.g., .NET, Java Enterprise Edition, and COM), or programming language, you do not want to maintain full type fidelity because you cannot assume all possible recipients can understand .NET-specific data types. Given this, SoapFormatter and XmlSerializer are ideal choices when you need to ensure as broad a reach as possible for the persisted tree of objects. Serializing Objects Using the BinaryFormatter You can use the BinaryFormatter type to illustrate how easy it is to persist an instance of the JamesBondCar to a physical file. Again, the two key methods of the BinaryFormatter type to be aware of are Serialize() and Deserialize(). • Serialize(): Persists an object graph to a specified stream as a sequence of bytes. • Deserialize(): Converts a persisted sequence of bytes to an object graph. Assume you have created an instance of JamesBondCar, modified some state data, and want to persist your spy mobile into a *.dat file. Begin by creating the *.dat file itself. You can achieve this by creating an instance of the System.IO.FileStream type. At this point, you can create an instance of the BinaryFormatter and pass in the FileStream and object graph to persist. Consider the following Main() method: // Be sure to import the System.Runtime.Serialization.Formatters.Binary // and System.IO namespaces. static void Main(string[] args) { Console.WriteLine("***** Fun with Object Serialization *****\n"); // Make a JamesBondCar and set state. JamesBondCar jbc = new JamesBondCar(); jbc.canFly = true; jbc.canSubmerge = false; jbc.theRadio.stationPresets = new double[]{89.3, 105.1, 97.1}; jbc.theRadio.hasTweeters = true; } // Now save the car to a specific file in a binary format. SaveAsBinaryFormat(jbc, "CarData.dat"); Console.ReadLine(); You implement the SaveAsBinaryFormat() method like this: static void SaveAsBinaryFormat(object objGraph, string fileName) { // Save object to a file named CarData.dat in binary. BinaryFormatter binFormat = new BinaryFormatter(); using(Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { binFormat.Serialize(fStream, objGraph); } 787