Serialize and DeSerialize : Serialization : File Stream C# Source Code


Custom Search

C# Source Code » File Stream » Serialization »

 

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

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo File Stream
» Serialization