Csharp/C Sharp/File Stream/Serialization — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 11:45, 26 мая 2010

Collection Serialization

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("\t" + s);
        }
        Console.WriteLine("\nSOAP people:");
        foreach (string s in soapPeople)
        {
            Console.WriteLine("\t" + s);
        }
    }
}


C# Serialization

/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 32 - .NET Frameworks Overview\Serialization
// copyright 2000 Eric Gunnerson
// file=serial.cs
// compile with: csc serial.cs
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
public class FrameworksOverviewSerialization
{
    public static void Main()
    {
        MyRow row = new MyRow();
        row.Add(new MyElement("Gumby"));
        row.Add(new MyElement("Pokey"));
        
        Console.WriteLine("Initial value");
        Console.WriteLine("{0}", row);
        
        // write to binary, read it back
        Stream streamWrite = File.Create("MyRow.bin");
        BinaryFormatter binaryWrite = new BinaryFormatter();
        binaryWrite.Serialize(streamWrite, row);
        streamWrite.Close();
        
        Stream streamRead = File.OpenRead("MyRow.bin");
        BinaryFormatter binaryRead = new BinaryFormatter();
        MyRow rowBinary = (MyRow) binaryRead.Deserialize(streamRead);
        streamRead.Close();
        
        Console.WriteLine("Values after binary serialization");
        Console.WriteLine("{0}", rowBinary);
        
        // write to SOAP (XML), read it back
        streamWrite = File.Create("MyRow.xml");
        SoapFormatter soapWrite = new SoapFormatter();
        soapWrite.Serialize(streamWrite, row);
        streamWrite.Close();
        
        streamRead = File.OpenRead("MyRow.xml");
        SoapFormatter soapRead = new SoapFormatter();
        MyRow rowSoap = (MyRow) soapRead.Deserialize(streamRead);
        streamRead.Close();
        
        Console.WriteLine("Values after SOAP serialization");
        Console.WriteLine("{0}", rowSoap);
    }
}
[Serializable]
public class MyElement
{
    public MyElement(string name)
    {
        this.name = name;
        this.cacheValue = 15;
    }
    public override string ToString()
    {
        return(String.Format("{0}: {1}", name, cacheValue));
    }
    string name;
    // this field isn"t persisted.
    [NonSerialized]
    int cacheValue;
}
[Serializable]
public class MyRow
{
    public void Add(MyElement my)
    {
        row.Add(my);
    }
    
    public override string ToString()
    {
        string temp = null;
        foreach (MyElement my in row)
        temp += my.ToString() + "\n"; 
        return(temp);
    }
    
    ArrayList row = new ArrayList();    
}


Deserialize

using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Employee : ISerializable {
    private string name;
    private int age;
    private string address;
    public Employee(string name, int age, string address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }
    private Employee(SerializationInfo info, StreamingContext context) {
        name = info.GetString("Name");
        age = info.GetInt32("Age");
        try {
            address = info.GetString("Address");
        } catch (SerializationException) {
            address = null;
        }
    }
    public string Name {
        get { return name; }
        set { name = value; }
    }
    public int Age {
        get { return age; }
        set { age = value; }
    }
    public string Address {
        get { return address; }
        set { address = value; }
    }
    public void GetObjectData(SerializationInfo inf, StreamingContext con) {
        inf.AddValue("Name", name);
        inf.AddValue("Age", age);
        if ((con.State & StreamingContextStates.File) == 0) {
            inf.AddValue("Address", address);
        }
    }
    public override string ToString() {
        StringBuilder str = new StringBuilder();
        str.AppendFormat("Name: {0}\r\n", Name);
        str.AppendFormat("Age: {0}\r\n", Age);
        str.AppendFormat("Address: {0}\r\n", Address);
        return str.ToString();
    }
}
public class MainClass {
    public static void Main(string[] args) {
        Employee roger = new Employee("R", 56, "L");
        Console.WriteLine(roger);
        Stream str = File.Create("r.bin");
        BinaryFormatter bf = new BinaryFormatter();
        bf.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
        bf.Serialize(str, roger);
        str.Close();
        str = File.OpenRead("r.bin");
        bf = new BinaryFormatter();
        roger = (Employee)bf.Deserialize(str);
        str.Close();
        Console.WriteLine(roger);
        str = File.Create("r.bin");
        bf = new BinaryFormatter();
        bf.Context = new StreamingContext(StreamingContextStates.File);
        bf.Serialize(str, roger);
        str.Close();
        str = File.OpenRead("r.bin");
        bf = new BinaryFormatter();
        roger = (Employee)bf.Deserialize(str);
        str.Close();
        Console.WriteLine(roger);
    }
}


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


illustrates binary serialization

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/

 /*
  Example15_19.cs illustrates binary serialization
*/
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
// the Customer class gives us something to serialize
[Serializable]
class Customer
{
  // some private data members
  private int CustomerNumber;
  private string CustomerName;
  private string CustomerCountry;
  // the WriteCustomer method formats info to the screen
  public void WriteCustomer()
  {
    Console.WriteLine("Customer Number: " + this.CustomerNumber);
    Console.WriteLine("Customer Name: " + this.CustomerName);
    Console.WriteLine("Customer Country: " + this.CustomerCountry);
  }
  // the constructor accepts all the info to create a customer
  public Customer(
    int newCustomerNumber, 
    string newCustomerName, 
    string newCustomerCountry)
  {
    this.CustomerNumber = newCustomerNumber;
    this.CustomerName = newCustomerName;
    this.CustomerCountry = newCustomerCountry;
  }
}
public class Example15_19 
{
  public static void Main() 
  {
    // create a new customer and dump to screen
    Customer MyCustomer = new Customer(1, "X Corporation", "France");
    MyCustomer.WriteCustomer();
    // Create a FileStream to hold the serialized customer
    FileStream serializeStream = new FileStream("c:\\MyCustomer.dat", 
     FileMode.Create);
    // use the CLR"s binary formatting support
    BinaryFormatter bf = new BinaryFormatter();
    // serialize the object
    bf.Serialize(serializeStream, MyCustomer);
    serializeStream.Flush();
    serializeStream.Close();
    // retrieve the serialized version to a second object and dump that
    FileStream retrieveStream = new FileStream("c:\\MyCustomer.dat",
     FileMode.Open);
    Customer NewCustomer = (Customer) bf.Deserialize(retrieveStream);
    NewCustomer.WriteCustomer();
  }
}


NonSerialized attributes

    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();
      // Now save this room to a binary stream.
      FileStream myStream = File.Create("RoomData.dat");
      BinaryFormatter myBinaryFormat = new BinaryFormatter();
      myBinaryFormat.Serialize(myStream, myAuto);
      myStream.Close();
      Console.WriteLine("Saved room to roomdata.dat.");
      // Read in the Room from the binary stream.
      Console.WriteLine("Reading room from binary file.");
      myStream = File.OpenRead("RoomData.dat");
      MyRoom roomFromDisk = (MyRoom)myBinaryFormat.Deserialize(myStream);
      Console.WriteLine(roomFromDisk.PetName + " is alive!");
      roomFromDisk.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!!!");      
    }
    }


Serial Employee class

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
class SoapTest
{
   public static void Main()
   {
      SerialEmployee emp1 = new SerialEmployee();
      SerialEmployee emp2 = new SerialEmployee();
      emp1.EmployeeID = 1;
      emp1.LastName = "B";
      emp1.FirstName = "K";
      emp1.YearsService = 12;
      emp1.Salary = 35000.50;
      emp2.EmployeeID = 2;
      emp2.LastName = "B";
      emp2.FirstName = "J";
      emp2.YearsService = 9;
      emp2.Salary = 23700.30;
      Stream str = new FileStream("soaptest.xml", FileMode.Create, FileAccess.ReadWrite);
      IFormatter formatter = new SoapFormatter();
      formatter.Serialize(str, emp1);
      formatter.Serialize(str, emp2);
      str.Close();
   }
}

[Serializable]
public class SerialEmployee
{
   public int EmployeeID;
   public string LastName;
   public string FirstName;
   public int YearsService;
   public double Salary;
   public SerialEmployee()
   {
      EmployeeID = 0;
      LastName = null;
      FirstName = null;
      YearsService = 0;
      Salary = 0.0;
   }
}


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


Serialize hiearchy classes

    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();
      // Now save this room to a binary stream.
      FileStream myStream = File.Create("RoomData.dat");
      BinaryFormatter myBinaryFormat = new BinaryFormatter();
      myBinaryFormat.Serialize(myStream, myAuto);
      myStream.Close();
      Console.WriteLine("Saved room to roomdata.dat.");
      // Read in the Room from the binary stream.
      Console.WriteLine("Reading room from binary file.");
      myStream = File.OpenRead("RoomData.dat");
      MyRoom roomFromDisk = (MyRoom)myBinaryFormat.Deserialize(myStream);
      Console.WriteLine(roomFromDisk.PetName + " is alive!");
      roomFromDisk.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!!!");      
    }
    }


Set XML tag name for Serialization

using System;
using System.IO;
using System.Xml.Serialization;
public class Serializer {
  public static void Main(string [] args) {
    Personnel personnel = CreatePersonnel();
    XmlSerializer serializer = new XmlSerializer(typeof(Personnel));
    using (FileStream stream = File.OpenWrite("Employees.xml")) {
      serializer.Serialize(stream, personnel);
    }
  }
  
  private static Personnel CreatePersonnel() {
    Personnel personnel = new Personnel();
    personnel.Employees = new Employee [] {new Employee()};
    personnel.Employees[0].FirstName = "Joe";
    personnel.Employees[0].MiddleInitial = "M";
    personnel.Employees[0].LastName = "Lee";
    
    personnel.Employees[0].Addresses = new Address [] {new Address()};
    personnel.Employees[0].Addresses[0].AddressType = AddressType.Home;
    personnel.Employees[0].Addresses[0].Street = new string [] {"999 Colluden"};
    personnel.Employees[0].Addresses[0].City = "Vancouver";
    personnel.Employees[0].Addresses[0].State = State.BC;
    personnel.Employees[0].Addresses[0].Zip = "V5V 4X7";
    
    personnel.Employees[0].HireDate = new DateTime(2001,1,1);
    
    return personnel;
  }
}

[Serializable]
public enum AddressType {
  Home,
  Office
}
[Serializable]
public enum State {
  [XmlEnum(Name="British C")]BC,
  [XmlEnum(Name="Sask")]SK
}
[Serializable]
public class Address {
  [XmlAttribute(AttributeName="type")]  public AddressType AddressType;
  [XmlElement(ElementName="street")]    public string[] Street;
  [XmlElement(ElementName="city")]      public string City;
  [XmlElement(ElementName="state")]     public State State;
  [XmlElement(ElementName="zip")]       public string Zip;
}
[Serializable]
public class TelephoneNumber {
  [XmlAttribute(AttributeName="type")] public AddressType AddressType;
  [XmlElement(ElementName="areacode")] public string AreaCode;
  [XmlElement(ElementName="exchange")] public string Exchange;
  [XmlElement(ElementName="number")]   public string Number;
}
[Serializable]
public class Employee {
  [XmlAttribute(AttributeName="firstname")]      public string FirstName;
  [XmlAttribute(AttributeName="middleinitial")]  public string MiddleInitial;
  [XmlAttribute(AttributeName="lastname")]       public string LastName;
  
  [XmlArray(ElementName="addresses")]
  [XmlArrayItem(ElementName="address")]      public Address [] Addresses;
  [XmlArray(ElementName="telephones")] 
  [XmlArrayItem(ElementName="telephone")]    public TelephoneNumber [] TelephoneNumbers;
  
  [XmlAttribute(AttributeName="hiredate")]   public DateTime HireDate;
}
[Serializable]
[XmlRoot(ElementName="personnel")]
public class Personnel {
  [XmlElement(ElementName="employee")]
  public Employee [] Employees;
}


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.ru")]
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();
    }
}


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


Working with the Serializable Attribute

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