Csharp/CSharp Tutorial/Network/SoapFormatter

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

Use SoapFormatter to Serialize an object to xml message

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
[Serializable]
class Employee
{
  private int NO;
  private string FirstName;
  private string LastName;
  public void WriteEmployee()
  {
    Console.WriteLine("Number: " + this.NO);
    Console.WriteLine("FirstName: " + this.FirstName);
    Console.WriteLine("LastName: " + this.LastName);
  }
  public Employee(int newNO, string newFirstName, string newLastName){
    this.NO = newNO;
    this.FirstName = newFirstName;
    this.LastName = newLastName;
  }
}
class MainClass
{
  public static void Main() 
  {
    Employee MyEmployee = new Employee(1, "X", "F");
    MyEmployee.WriteEmployee();
    FileStream serializeStream = new FileStream("c:\\MyEmployee.xml", FileMode.Create);
    SoapFormatter sf = new SoapFormatter();
    sf.Serialize(serializeStream, MyEmployee);
    serializeStream.Flush();
    serializeStream.Close();
    FileStream retrieveStream = new FileStream("c:\\MyEmployee.xml",FileMode.Open);
    Employee NewEmployee = (Employee) sf.Deserialize(retrieveStream);
    NewEmployee.WriteEmployee();
  }
}
Number: 1
FirstName: X
LastName: F
Number: 1
FirstName: X
LastName: F