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);
    }
}

   
     


Use SoapFormatter

   
 


using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;

class MainClass
{
    private static void BinarySerialize(ArrayList list)
    {
        using (FileStream str = File.Create("people.bin"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(str, list);
        }
    }

    private static ArrayList BinaryDeserialize()
    {
        ArrayList people = null;
        using (FileStream str = File.OpenRead("people.bin"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            people = (ArrayList)bf.Deserialize(str);
        }
        return people;
    }

    private static void SoapSerialize(ArrayList list)
    {
        using (FileStream str = File.Create("people.soap"))
        {
            SoapFormatter sf = new SoapFormatter();
            sf.Serialize(str, list);
        }
    }

    private static ArrayList SoapDeserialize()
    {
        ArrayList people = null;
        using (FileStream str = File.OpenRead("people.soap"))
        {
            SoapFormatter sf = new SoapFormatter(); 
            people = (ArrayList)sf.Deserialize(str);
        }
        return people;
    }
    public static void Main()
    {

        ArrayList people = new ArrayList();
        people.Add("G");
        people.Add("L");
        people.Add("A");

        BinarySerialize(people);
        SoapSerialize(people);

        ArrayList binaryPeople = BinaryDeserialize();
        ArrayList soapPeople = SoapDeserialize();
        Console.WriteLine("Binary people:");
        foreach (string s in binaryPeople)
        {
            Console.WriteLine("	" + s);
        }
        Console.WriteLine("
SOAP people:");
        foreach (string s in soapPeople)
        {
            Console.WriteLine("	" + s);
        }
    }
}

    


Serialize Class to Soap message

   

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

public class Serializer {

  public static void Main(string [] args) {
    StudentList personnel = CreateStudentList();
    IFormatter soapFormatter = new SoapFormatter();
    using (FileStream stream = File.OpenWrite("StudentListSoap.xml")) {
      soapFormatter.Serialize(stream,personnel);
    }
  }
  
  private static StudentList CreateStudentList() {
    StudentList personnel = new StudentList();
    personnel.Students = new Employee [] {new Employee()};
    personnel.Students[0].FirstName = "Apple";
    personnel.Students[0].MiddleInitial = "M";
    personnel.Students[0].LastName = "Bear";
    
    personnel.Students[0].Addresses = new Address [] {new Address()};
    personnel.Students[0].Addresses[0].AddressType = AddressType.Home;
    personnel.Students[0].Addresses[0].Street = new string [] {"Culloden"};
    personnel.Students[0].Addresses[0].City = "Vancouver";
    personnel.Students[0].Addresses[0].State = State.BC;
    personnel.Students[0].Addresses[0].Zip = "V5V 4X7";
    
    personnel.Students[0].StartDate = new DateTime(2006,10,12);
    
    return personnel;
  }
}

[Serializable]
public enum AddressType {
  Home,
  Office
}

[Serializable]
public enum State {
  BC, ON
}

[Serializable]
public class Address {
  public AddressType AddressType;
  public string[] Street;
  public string City;
  public State State;
  public string Zip;
}

[Serializable]
public class TelephoneNumber {
  public string AreaCode;
  public string Exchange;
  public string Number;
}

[Serializable]
public class Employee {
  public string FirstName;
  public string MiddleInitial;
  public string LastName;
  public Address [] Addresses;
  public TelephoneNumber [] TelephoneNumbers;
  public DateTime StartDate;
}

[Serializable]
public class StudentList {
  public Employee [] Students;
}

           
          


Serialize to SOAP based XML file


   

    using System;
  using System.IO;
  using System.Runtime.Serialization.Formatters.Binary;
  using System.Runtime.Serialization.Formatters.Soap;
  

    public class RoomApp
    {
    public static void Main()
    {
      // Make a room and listen to the tunes.
      Console.WriteLine("Made a My Room...");
      MyRoom myAuto = new MyRoom("My", 50, false, true);
      myAuto.TurnOnRadio(true);
      myAuto.GoUnderWater();

      // Save the same room into SOAP format.
      Console.WriteLine("Now saving room to XML file");
      FileStream myStream = File.Create("RoomData.xml");
      SoapFormatter myXMLFormat = new SoapFormatter();
      myXMLFormat.Serialize(myStream, myAuto);
      myStream.Close();

      // Read in the Room from the XML file.
      Console.WriteLine("Reading room from XML file.");
      myStream = File.OpenRead("RoomData.xml");
      MyRoom roomFromXML = (MyRoom)myXMLFormat.Deserialize(myStream);
      Console.WriteLine(roomFromXML.PetName + " is alive!");
      roomFromXML.TurnOnRadio(true);
      myStream.Close();
      
    }
    }  
  
  
  [Serializable]
    public class Radio
    {
    [NonSerialized]
    private int objectIDNumber = 9;

        public Radio(){}
    public void On(bool state)
    {
      if(state == true)
        Console.WriteLine("Music is on...");
      else
        Console.WriteLine("No tunes...");        
    }
    }


  [Serializable]
    public class Room
    {
    protected string petName;
    protected int maxInternetSpeed;
    protected Radio theRadio = new Radio();

        public Room(string petName, int maxInternetSpeed)
        {
      this.petName = petName;
      this.maxInternetSpeed = maxInternetSpeed;
        }
    public Room() {}

    public String PetName
    {
      get { return petName; }
      set { petName = value; }
    }
    public int MaxInternetSpeed
    {
      get { return maxInternetSpeed; }
      set { maxInternetSpeed = value; }
    }

    public void TurnOnRadio(bool state)
    {
      theRadio.On(state);
    }
    }


  [Serializable]
    public class MyRoom : Room
    {
    protected bool isFlightWorthy;
    protected bool isSeaWorthy;

    public MyRoom(string petName, int maxInternetSpeed, 
              bool canFly, bool canSubmerge)
      : base(petName, maxInternetSpeed)
        {
      this.isFlightWorthy = canFly;
      this.isSeaWorthy = canSubmerge;
    }
    public MyRoom(){}

    public void Fly()
    {
      if(isFlightWorthy)
        Console.WriteLine("Taking off!");
      else
        Console.WriteLine("Falling off cliff!");
    }

    public void GoUnderWater()
    {
      if(isSeaWorthy)
        Console.WriteLine("Diving....");
      else
        Console.WriteLine("Drowning!!!");      
    }
    }