11.3 Explicit Serialization

Consider a case in which a client wants to serialize a complex graph of objects to a file on disk. Furthermore, let's assume that the objects already support serialization (if not, the client's job is much harder). Fundamentally, there are two things the client needs to initiate an explicit serialization: an object reference identifying the root of the object graph, and a Stream reference identifying the place to serialize the object graph to.

Given these two references, the client needs some way to initiate the serialization and deserialization process. Since this is a common need, the Framework defines a standard interface called IFormatter that provides Serialize and Deserialize methods that work in terms of object and Stream references.

The Framework also provides two concrete implementations of this interface: the BinaryFormatter class (which lives in the System.Runtime.Serialization.Formatters.Binary namespace, and serializes object graphs using a binary format), and the SoapFormatter class (which lives in the System.Runtime.Serialization.Formatters.Soap namespace, and serializes object graphs as XML using SOAP Section 5 encoding rules).

Using these classes, clients can serialize graphs of objects with almost no code:

public void SerializeGraph(string file, object root) {
  Stream stm = new FileStream(file, FileMode.Create);  
  IFormatter fmt = new BinaryFormatter( );  
  fmt.Serialize(stm, root);
  stm.Flush( );
  stm.Close( );
}

When passed a target filename and the root of an object graph supporting serialization, SerializeGraph creates a new file and serializes the object graph into it in a binary format. Changing the serialization format to an XML representation of the object graph (using SOAP Section 5 encoding rules) is as simple as replacing the call to instantiate the BinaryFormatter with one to instantiate a SoapFormatter.

Deserialization is just as simplethe following code assumes an XML serialization format, and deserializes the contents of a file into an in-memory object graph. To use the object reference returned by the function in client code, downcast to the appropriate type:

public object DeserializeGraph(string file) {
  Stream stm = new FileStream(file, FileMode.Open); 
  IFormatter fmt = new SoapFormatter( );  
  object o = fmt.Deserialize(stm);
  stm.Close( );
  return o;
}


    Part II: Programming with the .NET Framework
    Part IV: API Quick Reference
     
    ASPTreeView.com
     
    Evaluation has ЖїіЅКХ·expired.
    Info...