using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
namespace SerializableTest
{
class Program
{
static void Main(string[] args)
{
SeriMethod();
DeseriMethod();
}
static void SeriMethod()
{
Person per = new Person(27, "David");
Stream str = File.Open(@"C:\SerializableTest.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(str, per);
Person perSoap = new Person(37, "Old David");
Stream strSoap = File.Open(@"C:\SerializableTest_Soap.dat", FileMode.Create);
SoapFormatter soapFor = new SoapFormatter();
soapFor.Serialize(strSoap, perSoap);
str.Close();
strSoap.Close();
}
static void DeseriMethod()
{
Stream str = File.Open(@"C:\SerializableTest.dat", FileMode.Open);
Stream strSoap = File.Open(@"C:\SerializableTest_Soap.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
SoapFormatter soapFor = new SoapFormatter();
object o = bf.Deserialize(str);
object Soap = soapFor.Deserialize(strSoap);
Person per = (Person)o;
Person perSoap = (Person)oSoap;
if (per != null)
Console.WriteLine("Binary DeSerialized Person aged:{0} name:{1}", per.age, per.name);
if (perSoap != null)
Console.WriteLine("Soap DeSerialized Person aged:{0} name:{1}", perSoap.age, perSoap.name);
str.Close();
strSoap.Close();
}
}
[Serializable]
class Person
{
public int age;
//[NonSerialized]
public string name = string.Empty;
public Person(int argAge, string argName)
{
age = argAge;
name = argName;
}
}
}
Result:
ÿ?! Ȁ 䝓敲楡汩穡扬敔敳琬⁖敲獩潮㴱⸰⸰⸰Ⱐ䍵汴畲攽湥畴牡氬⁐畢汩捋敹呯步渽湵汬ԁ 卥物慬楺慢汥呥獴⹐敲獯渂 慧攄湡浥ࠂ ̀ Մ慶楤
--------------------------------------------------------------------------------------------
Binary DeSerialized Person aged:27 name:David
Soap DeSerialized Person aged:37 name:Old David
Press any key to continue . . .