Pages

Wednesday, 30 April 2014

Serialize and Deserialize in C#


Hi,


Here you are gonna learn about Serialization & Deserialization in C#.

Definition

Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called Deserialization (From MSDN).


Description

This project serializes a list of names and saves it, then it deserializes the file and use it as required. so lets go;

Steps

1. Open Visual Studio -> New Project -> Windows Form Application with a name 
    SerializeDeserialize

2. Now follow the steps;
  • Add 1 combobox, 1 textbox, 2 labels and 1 button to your form
  • Change the combobox Name to ComboSavedList and textbox Name to txtNew (from properties dialog box)
  • Now design your form as shown in the below screenshot. 




3. Now double click on the button Save and paste the below code

           //checking if textbox contains text
            if (txtNew.Text.Length > 0)
            {
                string FilePath = Path.Combine(Application.StartupPath, "Data.src");
                string NewData = txtNew.Text;

                //adding the new data to the list
                Datalist.Add(NewData);
                //Calling the Serialize function
                Serialize(FilePath, Datalist);
                //Deserializing the saved data
                Deserialize(FilePath);
                MessageBox.Show("Saved");

4. Also double click on the Form and paste the below code in Form_Load event handler
    
          //Deserialize the file and load it on combobox on application startup
           string FilePath = Path.Combine(Application.StartupPath, "Data.src");
            if (File.Exists(FilePath))
                Deserialize(FilePath);


5. Now update your Form.cs as shown in the below code

    Form1.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace SerializeDeserialize
{
    public partial class Form1 : Form
    {
        //String list for saving the data       
        List<string> Datalist = new List<string>();

        public Form1()
        {
            InitializeComponent();
        }

        //Serialization
        void Serialize(string FileName, object datalist)
        {
            try
            {
                //checking if file exists
                if (File.Exists(FileName))
                    File.Delete(FileName);

                using (FileStream fs = new FileStream(FileName, FileMode.Create))
                {
                    BinaryFormatter bin = new BinaryFormatter();
                    bin.Serialize(fs, datalist);
                    fs.Close();
                }

            }
            catch
            {
            }

        }

        //Deserialization
        void Deserialize(string FileName)
        {
            try
            {

                if (File.Exists(FileName))
                {
                    BinaryFormatter bin = new BinaryFormatter();
                    using (FileStream fs = new FileStream(FileName, FileMode.Open))
                    {
                        Datalist = (List<string>)bin.Deserialize(fs);
                        fs.Close();

                    }
                    //Setting the combobox source as Datalist
                    ComboSavedList.DataSource = Datalist;

                }

            }
            catch
            {
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            //checking if textbox contains text
            if (txtNew.Text.Length > 0)
            {
                string FilePath = Path.Combine(Application.StartupPath, "Data.src");
                string NewData = txtNew.Text;

                //adding the new data to the list
                Datalist.Add(NewData);
                //Calling the Serialize function
                Serialize(FilePath, Datalist);
                //Deserializing the saved data
                Deserialize(FilePath);
                MessageBox.Show("Saved");

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string FilePath = Path.Combine(Application.StartupPath, "Data.src");
            if (File.Exists(FilePath))
                Deserialize(FilePath);
        }
    }
}


Code Explanation

  • On running the project, add names to the textbox (txtNew) and click on Save. The name will be listed in the combobox (comboSavedList).
  • On clicking the Save button, the data in the list (Datalist) is Serialized and saved in the Application's startup path with a name Data.src. (See the Screenshot below),Then  the file is Deserialized and the names are listed in the combobox.




  • Also the file will be deserialized and loaded to the combobox on application startup.


Output

Run the project and enter names to the textbox and click on Save (Screenshot 1). See the name is listed in the combobox. Now restart the application, the combobox still holds the names (Screenshot 2). 


Screenshot 1 : Saving the Data
Screenshot 2 : Saved data on application restart

Conclusion

Congrats, you have learned to Serialize and Deserialize in C#. Enjoy :-)
In case of any errors / doubts feel free to drop a comment.


See Also


3 comments:

  1. Good one...Thanks

    ReplyDelete
  2. Thanks, it helped me a lot :-)

    ReplyDelete
  3. Nice Post...really helpful

    ReplyDelete

 

About Me

I am Tijo Tom, a Computer Engineer from India.Right from my schooling, I had a passion for Programming, PC Tricks, Virus Creation and Hacking.

I started this blog on Jan 1, 2014 to share my views and ideas with the world.

You can know more about me on