using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Point2D
{
public int X;
public int Y;
}
class MyMainClass
{
public static void Main()
{
Point2D My2DPoint = new Point2D();
My2DPoint.X = 100;
My2DPoint.Y = 200;
Stream WriteStream = File.Create("Point2D.bin");
BinaryFormatter BinaryWrite = new BinaryFormatter();
BinaryWrite.Serialize(WriteStream, My2DPoint);
WriteStream.Close();
Point2D ANewPoint = new Point2D();
Console.WriteLine("New Point Before Deserialization: ({0}, {1})", ANewPoint.X, ANewPoint.Y);
Stream ReadStream = File.OpenRead("Point2D.bin");
BinaryFormatter BinaryRead = new BinaryFormatter();
ANewPoint = (Point2D)BinaryRead.Deserialize(ReadStream);
ReadStream.Close();
Console.WriteLine("New Point After Deserialization: ({0}, {1})", ANewPoint.X, ANewPoint.Y);
}
}
Month: February 2011
Use XML Serialization with Custom Objects
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
public class SerializeXml {
private static void Main() {
CarList catalog = new CarList("New List", DateTime.Now.AddYears(1));
Car[] cars = new Car[2];
cars[0] = new Car("Car 1", 12342.99m);
cars[1] = new Car("Car 2", 21234123.9m);
catalog.Cars = cars;
XmlSerializer serializer = new XmlSerializer(typeof(CarList));
FileStream fs = new FileStream("CarList.xml", FileMode.Create);
serializer.Serialize(fs, catalog);
fs.Close();
catalog = null;
// Deserialize the order from the file.
fs = new FileStream("CarList.xml", FileMode.Open);
catalog = (CarList)serializer.Deserialize(fs);
// Serialize the order to the Console window.
serializer.Serialize(Console.Out, catalog);
}
}
[XmlRoot("carList")]
public class CarList {
[XmlElement("catalogName")]
public string ListName;
// Use the date data type (and ignore the time portion in the serialized XML).
[XmlElement(ElementName="expiryDate", DataType="date")]
public DateTime ExpiryDate;
[XmlArray("cars")]
[XmlArrayItem("car")]
public Car[] Cars;
public CarList() {
}
public CarList(string catalogName, DateTime expiryDate) {
this.ListName = catalogName;
this.ExpiryDate = expiryDate;
}
}
public class Car {
[XmlElement("carName")]
public string CarName;
[XmlElement("carPrice")]
public decimal CarPrice;
[XmlElement("inStock")]
public bool InStock;
[XmlAttributeAttribute(AttributeName="id", DataType="integer")]
public string Id;
public Car() {
}
public Car(string carName, decimal carPrice) {
this.CarName = carName;
this.CarPrice = carPrice;
}
}
Three types of Serialization: Binary, Soap, XML
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;
using System.Collections;
[Serializable]
public class Radio {
public bool hasTweeters;
public bool hasSubWoofers;
public double[] stationPresets;
[NonSerialized]
public string radioID = "001";
}
[Serializable]
public class Car {
public Radio theRadio = new Radio();
public bool isHatchBack;
}
[Serializable, XmlRoot(Namespace = "http://www.yoursite.com")]
public class JamesBondCar : Car {
public JamesBondCar(bool SkyWorthy, bool SeaWorthy) {
canFly = SkyWorthy;
canSubmerge = SeaWorthy;
}
public JamesBondCar() { }
[XmlAttribute]
public bool canFly;
[XmlAttribute]
public bool canSubmerge;
}
class Program {
static void Main(string[] args) {
JamesBondCar jbc = new JamesBondCar();
jbc.canFly = true;
jbc.canSubmerge = false;
jbc.theRadio.stationPresets = new double[] { 89.3, 105.1, 97.1 };
jbc.theRadio.hasTweeters = true;
BinaryFormatter binFormat = new BinaryFormatter();
Stream fStream = new FileStream("CarData.dat",FileMode.Create, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, jbc);
fStream.Close();
fStream = File.OpenRead("CarData.dat");
JamesBondCar carFromDisk =(JamesBondCar)binFormat.Deserialize(fStream);
Console.WriteLine("Can this car fly? : {0}", carFromDisk.canFly);
fStream.Close();
SoapFormatter soapForamt = new SoapFormatter();
fStream = new FileStream("CarData.soap",FileMode.Create, FileAccess.Write, FileShare.None);
soapForamt.Serialize(fStream, jbc);
fStream.Close();
XmlSerializer xmlForamt = new XmlSerializer(typeof(JamesBondCar),new Type[] { typeof(Radio), typeof(Car) });
fStream = new FileStream("CarData.xml",FileMode.Create, FileAccess.Write, FileShare.None);
xmlForamt.Serialize(fStream, jbc);
fStream.Close();
ArrayList myCars = new ArrayList();
myCars.Add(new JamesBondCar(true, true));
myCars.Add(new JamesBondCar(true, false));
myCars.Add(new JamesBondCar(false, true));
myCars.Add(new JamesBondCar(false, false));
fStream = new FileStream("CarCollection.xml",FileMode.Create, FileAccess.Write, FileShare.None);
xmlForamt = new XmlSerializer(typeof(ArrayList),new Type[] { typeof(JamesBondCar), typeof(Car), typeof(Radio) });
xmlForamt.Serialize(fStream, myCars);
fStream.Close();
}
}
Serialize and DeSerialize
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
class Program {
static void Main(string[] args) {
Person me = new Person();
me.Age = 38;
me.WeightInPounds = 200;
Console.WriteLine(me.Age);
Console.WriteLine(me.WeightInPounds);
Stream s = File.Open("Me.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(s, me);
s.Close();
s = File.Open("Me.dat", FileMode.Open);
bf = new BinaryFormatter();
object o = bf.Deserialize(s);
Person p = o as Person;
if (p != null)
Console.WriteLine("DeSerialized Person aged: {0} weight: {1}", p.Age, p.WeightInPounds);
s.Close();
}
}
[Serializable]
public class Person {
public Person() {
}
public int Age;
public int WeightInPounds;
}
Deserialize Object
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[Serializable]
public class BookRecord {
public String title;
public int asin;
public BookRecord(String title, int asin) {
this.title = title;
this.asin = asin;
}
}
public class DeserializeObject {
public static void Main() {
FileStream streamIn = new FileStream(@"book.obj", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
BookRecord book = (BookRecord)bf.Deserialize(streamIn);
streamIn.Close();
Console.Write(book.title + " " + book.asin);
}
}
Use Serializable attribute to mark a class
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[Serializable]
public class BookRecord {
public String title;
public int asin;
public BookRecord(String title, int asin) {
this.title = title;
this.asin = asin;
}
}
public class SerializeObject {
public static void Main() {
BookRecord book = new BookRecord("title",123456789);
FileStream stream = new FileStream(@"book.obj",FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, book);
stream.Close();
}
}
Use Serializable attribute to mark a generic class
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class SampleCollection<T> : List<T> {
private int _intData;
private string _stringData;
public SampleCollection(int intData, string stringData) {
this._intData = intData;
this._stringData = stringData;
}
public int IntVal {
get { return this._intData; }
}
public string StrVal {
get { return this._stringData; }
}
}
public class TypeSafeSerializer {
private TypeSafeSerializer() { }
public static void AddValue<T>(String name, T value, SerializationInfo serInfo) {
serInfo.AddValue(name, value);
}
public static T GetValue<T>(String name, SerializationInfo serInfo) {
T retVal = (T)serInfo.GetValue(name, typeof(T));
return retVal;
}
}
public class MainClass {
public static void Main() {
SampleCollection<string> strList = new SampleCollection<string>(111, "Value1");
strList.Add("Val1");
strList.Add("Val2");
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, strList);
stream.Seek(0, SeekOrigin.Begin);
SampleCollection<string> newList = (SampleCollection<string>)formatter.Deserialize(stream);
Console.Out.WriteLine(newList.IntVal);
Console.Out.WriteLine(newList.StrVal);
foreach (string listValue in newList)
Console.Out.WriteLine(listValue);
}
}

