Friday, January 4, 2013
Serialization in .Net
Serialization is a process by which we can save the state of the object by converting the object in to stream of bytes.These bytes can then be stored in database, files, memory etc.These bytes are suitable for transmission (e.g. over the internet) or storage (e.g. on disk). What is it ? When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because .Net framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert it to a different format. This conversion is called SERIALIZATION. Uses for Serialization Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications. Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute attribute even if the class also implements the ISerializable interface to control the serialization process. All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. The default serialization process excludes fields that are marked with the NonSerializedAttribute attribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply the NonSerializedAttribute attribute to that field Below is a simple code of serializing the object. MyObject objObject = new MyObject(); objObject.Value = 100; // Serialization using SoapFormatter SoapFormatter formatter = new SoapFormatter(); Stream objFileStream = new FileStream("c:\\MyFile.xml", FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(objFileStream, objObject); objFileStream.Close(); Below is simple code which shows how to deserialize an object. //De-Serialization Stream objNewFileStream = new FileStream("c:\\MyFile.xml", FileMode.Open, FileAccess.Read, FileShare.Read); MyObject objObject =(MyObject)formatter.Deserialize(objNewFileStream); objNewFileStream.Close();
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment