C# Serialization
// 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 now
// that the file is associated with your program.
Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
Console.WriteLine("Writing Employee Information");
bformatter.Serialize(stream, mp);
stream.Close();
Stream stream = File.Open("Categories.dat", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, categories);
stream.Close();
namespace MyObjSerial
{
[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;
}
}
}
//Open the file written above and read values from it.
stream = File.Open("EmployeeInfo.osl", FileMode.Open);
bformatter = new BinaryFormatter();
Console.WriteLine("Reading Employee Information");
mp = (Employee)bformatter.Deserialize(stream);
stream.Close();
Console.WriteLine("Employee Id: {0}",mp.EmpId.ToString());
Console.WriteLine("Employee Name: {0}",mp.EmpName);
Stream stream = File.Open("Categories.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
categories = new List<Category>();
categories = (List<Category>)bf.Deserialize(stream);
foreach (var cat in categories)
{
Console.WriteLine("Cat: " + cat.Description + " number: " + cat.CategoryNumber);
}