[C#]
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
namespace NazTek.Sample.Serialization
{
public class TestSerialization
{
private const string DATA_FILE = @"C:\Documents and Settings\All Users\Desktop\temp.xml";
public static void Main (string[] s)
{
TestSerialization ts = new TestSerialization();
ts.Serialize();
ts.DeSerialize();
}
public void Serialize()
{
Person employee = new Employee("E123", "Bob", 35);
Stream stream = File.Open(DATA_FILE, FileMode.Create);
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(stream, employee);
stream.Close();
}
public void DeSerialize()
{
Stream stream = File.Open(DATA_FILE, FileMode.Open);
SoapFormatter formatter = new SoapFormatter();
Employee employee = (Employee)formatter.Deserialize(stream);
Console.WriteLine("The employee's id is {0}, name is {1} and age is {2}", employee.EmployeeId, employee.Name, employee.Age);
Console.ReadLine();
stream.Close();
}
}
/// <summary>
/// A class whose code is unavailable for modification but is in need of serialization
/// </summary>
public class Person : ISerializable
{
private int _age;
private string _name;
private DateTime _instanceDate;
public string Name { get { return _name; } }
public int Age { get { return _age; } }
public DateTime InstanceDate { get { return _instanceDate; } }
public Person(string name, int age)
{
_age = age;
_name = name;
_instanceDate = DateTime.Now;
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Age", _age);
info.AddValue("Name", _name);
info.AddValue("InstanceDate", _instanceDate);
}
}
/// <summary>
/// Class to serialize
/// </summary>
[Serializable]
public class Employee : Person
{
private string _employeeId;
public string EmployeeId { get { return _employeeId; } }
public Employee(string employeeId, string name, int age)
: base(name, age)
{
_employeeId = employeeId;
}
public Employee(SerializationInfo info, StreamingContext context)
: base(info.GetValue("Name", Type.GetType("System.String")).ToString(), Convert.ToInt32(info.GetValue("Age", Type.GetType("System.Int32"))))
{
_employeeId = info.GetValue("EmployeeId", Type.GetType("System.String")).ToString();
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("EmployeeId", _employeeId);
}
}
}