Hi Everyone,

Today, I am coming up with the topic of “serialization in .net framework” .  There are three types of serialization techniques present in the .net framework. They are briefly explained as follows:

1) Binary Serialization
2) XML serialization
3) Soap Serialization

In this article, I will not focus on the theoreotical part rather will focus on how you can implement these concepts in the simple application.

Let us consider a sample application of Notepad Font. As we know, when we open a notepad application, we see the font of the text which we have set earlier at the last execution of notepad.

( Please note: This is not relevant to a particular file. Every file is opened in the same font which is set earlier in notepad )

Following is the code for binary serialization in the .cs file:

MainFont obj = new MainFont();
obj.Fnt =  RTBArea.Font;

FileStream fs;

fs = new FileStream(@”font.dat”, FileMode.Create, FileAccess.Write,  FileShare.Read);

BinaryFormatter binF = new BinaryFormatter();

binF.Serialize(fs, obj);


In the above code, MainFont is the class whose namespace is as follows:

namespace Notepad
    public class MainFont
              private Font fnt;
              public Font Fnt
                      get { return fnt; }
                      set { fnt = value; }

Using the above code, you will be able to serialize the font set by the user in your notepad ( i.e. Rich Text Box )

Now, we have to deserialize the object which we have saved earlier.

To deserialize the object, write the following code in the load event of the application:

FileStream fsw;
            MainFont mf = new MainFont();

             fsw = new FileStream(@”font.dat”, FileMode.Open, FileAccess.Read,FileShare.Read);

             BinaryFormatter binF1 = new BinaryFormatter();
             mf = (MainFont)binF1.Deserialize(fsw);

            RTBArea.Font = mf.Fnt;

By using the above code, it will deserialize the font object present in the font.dat file and the font is assigned to the RTBArea font.

I have provided with the code for the Binary serialization in this article. If you want to implement soap and xml serialization, then you just have to use the XMLSerializer class and use references “System.Runtime.Serialization.Formatters.Soap” and “System.Runtime.Serialization.Formatters.xml”.

Note: For using the XMLSerializer, the members of the class should be public.

Enjoy 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s