IFormatter Interface is pretty handy to serialization! You can use it with BinaryFormatter Class. This is a very simple example of object serialization.
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iformatter.aspx http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx
----------------------------------------------------------------------------------------------------
<Car.cs>
using System.Linq;
using System.Text;
namespace Model
{
[Serializable]
public class Car
{
public int Price { get; set; }
public string Name { get; set; }
}
}
----------------------------------------------------------------------------------------------------
<Program.cs>
using Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace Serialization
{
class Program
{
static void Main(string[] args)
{
SerializeCar();
DeserializeCar();
}
private static void SerializeCar()
{
//Instantiate a new Car
Car car = new Car { Name = "BMW", Price = 70000 };
//Instantiate a new BinaryFormatter
IFormatter formatter = new BinaryFormatter();
//Create a new FileStream
Stream stream = new FileStream("car.obj", FileMode.Create, FileAccess.Write, FileShare.None);
//Use the formatter to serialize the Car object using the stream
formatter.Serialize(stream, car);
//close the stream
stream.Close();
}
private static void DeserializeCar()
{
//Create a new FileStream to read the file
Stream stream = new FileStream("car.obj", FileMode.Open, FileAccess.Read, FileShare.Read);
IFormatter formatter = new BinaryFormatter();
//Use the formatter to deserialize the Car object from file
//Note: The car needs to be cast back to type Car
Car car = (Car)formatter.Deserialize(stream);
Console.WriteLine("{0} is deserialized", car.Name);
}
}
}
----------------------------------------------------------------------------------------------------



