Thursday, April 30, 2009

C# - How to Serialize/Deserialize

As you know, when you want to send an object to another process, or transmit an object across the network (LAN, Intranet, WAN, Internet), you need to "serialize" the object. Serialization is the process of converting an object into a linear sequence of bytes and Deserialization is the process of converting a previously serialized sequence of bytes into an object.

Serialization has been a key part of .NET since version 1.0 and .NET Framework, implemented "Serialization" in the "System.Runtime.Serialization" namespace, and to serialize an object you can choose between, Binary, SOAP, XML, and custom serialization. There are libraries to serialize to special formats like comma delimited, etc ... too.


C# - How to Create a serializable (and deserializable) custom class
You need to add [Serializable] attribute to your class. The default handling of serialization, serialize all the members, including private members.
It's possible to customize and control serialization of your class depends on custom requirements either to improve efficiency.

C# - How to disable serialization of a member
Just add [NonSerialized] attribute in front of the specific member, it causes to exclude that member from serialized version of the object. sometimes, we need to reduce the size of our object to transfer it across the network then you can bypass calculable members and regenerate them all back in destination.

To enable your class to initialize the [NonSerialized] members automatically use OnDeserialization, this method will be called after deserializing is complete.


using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
...
private void btnSerialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, txt4Serialization.Text);
}
}

private void btnDeSerialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
txtDeserialized.Text = (string)bf.Deserialize(fs);
}
}


Share/Bookmark

No comments: