using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Employee : ISerializable {
private string name;
private int age;
private string address;
public Employee(string name, int age, string address) {
this.name = name;
this.age = age;
this.address = address;
}
private Employee(SerializationInfo info, StreamingContext context) {
name = info.GetString("Name");
age = info.GetInt32("Age");
try {
address = info.GetString("Address");
} catch (SerializationException) {
address = null;
}
}
public string Name {
get { return name; }
set { name = value; }
}
public int Age {
get { return age; }
set { age = value; }
}
public string Address {
get { return address; }
set { address = value; }
}
public void GetObjectData(SerializationInfo inf, StreamingContext con) {
inf.AddValue("Name", name);
inf.AddValue("Age", age);
if ((con.State & StreamingContextStates.File) == 0) {
inf.AddValue("Address", address);
}
}
public override string ToString() {
StringBuilder str = new StringBuilder();
str.AppendFormat("Name: {0}\r\n", Name);
str.AppendFormat("Age: {0}\r\n", Age);
str.AppendFormat("Address: {0}\r\n", Address);
return str.ToString();
}
}
public class MainClass {
public static void Main(string[] args) {
Employee roger = new Employee("R", 56, "L");
Console.WriteLine(roger);
Stream str = File.Create("r.bin");
BinaryFormatter bf = new BinaryFormatter();
bf.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
bf.Serialize(str, roger);
str.Close();
str = File.OpenRead("r.bin");
bf = new BinaryFormatter();
roger = (Employee)bf.Deserialize(str);
str.Close();
Console.WriteLine(roger);
str = File.Create("r.bin");
bf = new BinaryFormatter();
bf.Context = new StreamingContext(StreamingContextStates.File);
bf.Serialize(str, roger);
str.Close();
str = File.OpenRead("r.bin");
bf = new BinaryFormatter();
roger = (Employee)bf.Deserialize(str);
str.Close();
Console.WriteLine(roger);
}
}