Tuesday, February 28, 2012

Serialize & De-serialize your business objects to data file



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

namespace ObjectToDatabase
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new Employee object
            Employee employee = new Employee();
            employee.EmpId = 1;
            employee.EmpName = "Kaushik Kumar Mistry";

            Stream stream = File.Open("EmployeeInfo.dat", FileMode.Create);
            BinaryFormatter bformatter = new BinaryFormatter();

            Console.WriteLine("Writing Employee Information to EmployeeInfo.dat file.");
            bformatter.Serialize(stream, employee);
            stream.Close();

            //Open the file written above and read values from it.
            stream = File.Open("EmployeeInfo.dat", FileMode.Open);
            bformatter = new BinaryFormatter();

            Console.WriteLine("Reading Employee Information from EmployeeInfo.dat file.");
            employee = (Employee)bformatter.Deserialize(stream);
            stream.Close();

            Console.WriteLine("Employee Id: {0}", employee.EmpId.ToString());
            Console.WriteLine("Employee Name: {0}", employee.EmpName);
            Console.ReadKey();
        }
    }

    [Serializable]
    public class Employee : ISerializable
    {
        public int EmpId{get;set;}
        public string EmpName { get; set; }

        //Default constructor.
        public Employee()
        {
        }

        //Deserialization constructor.
        public Employee(SerializationInfo info, StreamingContext ctxt)
        {
            EmpId = (int)info.GetValue("EmployeeId", typeof(int));
            EmpName = (String)info.GetValue("EmployeeName", typeof(string));
        }

        //Serialization function.
        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
        {
            info.AddValue("EmployeeId", EmpId);
            info.AddValue("EmployeeName", EmpName);
        }
    }
}

Post a Comment