using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace Serialization__Binary__Ex1
{
class Program
{
static void Main(string[] args)
{
////Create a new Employee object
Employee emp = new Employee();
emp.EmpId = 62;
emp.EmpName = "Kawser";
///* Serialize the object to a sample file */
//// Open a file and serialize the object into it in binary format.
//// EmployeeInfo.osl is the file that we are creating.
//// Note:- you can give any extension you want for your file
//// If you use custom extensions, then the user will know
//// that the file is associated with your program.
Stream stream1 = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
Console.WriteLine("Writing Employee Information");
bformatter.Serialize(stream1, emp);
stream1.Close();
/*Deserialize the values by reading it from the file */
//Clear mp for further usage.
//Open the file written above and read values from it.
Stream stream2 = File.Open("EmployeeInfo.osl", FileMode.Open);
BinaryFormatter bformatter2 = new BinaryFormatter();
Console.WriteLine("Reading Employee Information");
Employee emp2 = (Employee) bformatter2.Deserialize(stream2);
stream2.Close();
Console.WriteLine("Employee Id: {0}", emp2.EmpId.ToString());
Console.WriteLine("Employee Name: {0}", emp2.EmpName);
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Serialization__Binary__Ex1
{
[Serializable()] //Set this attribute to all the classes that want to serialize
public class Employee : ISerializable //derive your class from ISerializable
{
public int EmpId;
public string EmpName;
//Default constructor
public Employee()
{
EmpId = 0;
EmpName = null;
}
//Serialization function.
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
//You can use any custom name for your name-value pair. But make sure you
// read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
// then you should read the same with "EmployeeId"
info.AddValue("EmployeeId", EmpId);
info.AddValue("EmployeeName", EmpName);
}
//Deserialization constructor.
public Employee(SerializationInfo info, StreamingContext ctxt)
{
//Get the values from info and assign them to the appropriate properties
EmpId = (int)info.GetValue("EmployeeId", typeof(int));
EmpName = (String)info.GetValue("EmployeeName", typeof(string));
}
}
}