Friday, January 25, 2008

Serialization of data using binary formatters in C#

Sometimes our program needs to save objects and data on hard drive. It is actually a process to preserve state of an object on the hard drive. Microsoft.Net provides a mechanism called serialization and the reverse process by which we load the state of object again is called the deserialization.

There are two methods to perform serialization knows as binary and soap. In this article I’ll use binary serialization and I’ll try to keep the things simple in this article. So, I’ll just try to serialize text to hard drive and then deserialize it again. In some later article I’ll show you how to serialize application class objects to hard drive.

First of all include following namespaces:

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

let say we want to serialize some text from the text box and here is the code:

FileStream fs = new FileStream("c:\\SerializedData.Data", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, this.textBox1.Text);
fs.Close();

Now, you have serialized text in a data file on the hard drive. In order to deserialize it use the following code and show deserialized data in a text box.

FileStream fs = new FileStream("c:\\SerializedData.Data", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
string data = (string)bf.Deserialize(fs);
fs.Close();
this.textBox1.Text = data;

No comments: