Csharp/CSharp Tutorial/File Directory Stream/Binary Serialization — различия между версиями

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

Версия 15:31, 26 мая 2010

Binary Custom Serialization

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class MyClass : ISerializable
{
  public string MyStringValue;
  public int MyIntValue;
  public MyClass(string s, int i){ 
      MyStringValue = s; 
      MyIntValue = i;
    }
  public void GetObjectData(SerializationInfo si, StreamingContext ctx)
  {
    Console.WriteLine("[GetObjectData] Context State: {0}", ctx.State.ToString());
    si.AddValue("MyStringValue", MyStringValue.ToUpper());
    si.AddValue("MyIntValue", MyIntValue);
  }
  private MyClass(SerializationInfo si, StreamingContext ctx)
  {
    Console.WriteLine("[ctor] Context State: {0}",ctx.State.ToString());
    MyStringValue = si.GetString("MyStringValue");
    MyIntValue = si.GetInt32("MyIntValue");
  }
}
public class MainClass
{
  public static int Main(string[] args)
  {
    MyClass myAuto = new MyClass("Sid", 50);
    Stream myStream = File.Create("MyData.dat");
    
    BinaryFormatter myBinaryFormat = new BinaryFormatter();
    myBinaryFormat.Serialize(myStream, myAuto);
    myStream.Close();
    myStream = File.OpenRead("MyData.dat");
    MyClass carFromDisk = (MyClass)myBinaryFormat.Deserialize(myStream);
    Console.WriteLine("{0} is alive!\n", carFromDisk.MyStringValue);
    myStream.Close();
    return 0;
  }
}
[GetObjectData] Context State: All
[ctor] Context State: All
SID is alive!

Customized Serialization

using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Employee : ISerializable
{
    public string name;
    public int age;
    public 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");
        address = info.GetString("Address");
    }
    public void GetObjectData(SerializationInfo inf, StreamingContext con)
    {
        // Always serialize the Employee"s name and age.
        inf.AddValue("Name", name);
        inf.AddValue("Age", age);
        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 anEmployee = new Employee("Employee", 6, "London");
        Stream str = File.Create("anEmployee.bin");
        BinaryFormatter bf = new BinaryFormatter();
        bf.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
        bf.Serialize(str, anEmployee);
        str.Close();
        str = File.OpenRead("anEmployee.bin");
        bf = new BinaryFormatter();
        anEmployee = (Employee)bf.Deserialize(str);
        str.Close();
        Console.WriteLine(anEmployee);
    }
}
Name: Employee
Age: 6
Address: London

Implementing System.Runtime.Serialization.ISerializable

using System;
using System.Runtime.Serialization;
[Serializable]
class EncryptableDocument :ISerializable
{
  public EncryptableDocument(){ }
  enum Field
  {
      Title,
      Data
  }
  public string Title;
  public string Data;
  public static string Encrypt(string data)
  {
      string encryptedData = data;
      return encryptedData;
  }
  public static string Decrypt(string encryptedData)
  {
      string data = encryptedData;
      return data;
  }
  public void GetObjectData(SerializationInfo info, StreamingContext context)
  {
      info.AddValue(Field.Title.ToString(), Title);
      info.AddValue(Field.Data.ToString(), Encrypt(Data));
  }
  public EncryptableDocument(SerializationInfo info, StreamingContext context)
  {
      Title = info.GetString(Field.Title.ToString());
      Data = Decrypt(info.GetString(Field.Data.ToString()));
  }
}

Serialization of an object list in binary form

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
[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;
    [NonSerialized]
    int cacheValue;
}
[Serializable]
public class MyElementList
{
    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();    
}
class MainClass
{
    public static void Main()
    {
        MyElementList row = new MyElementList();
        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("MyElementList.bin");
        BinaryFormatter binaryWrite = new BinaryFormatter();
        binaryWrite.Serialize(streamWrite, row);
        streamWrite.Close();
        
        Stream streamRead = File.OpenRead("MyElementList.bin");
        BinaryFormatter binaryRead = new BinaryFormatter();
        MyElementList rowBinary = (MyElementList) binaryRead.Deserialize(streamRead);
        streamRead.Close();
        
        Console.WriteLine("Values after binary serialization");
        Console.WriteLine("{0}", rowBinary);
        
    }
}
Initial value
Gumby: 15
Pokey: 15
Values after binary serialization
Gumby: 0
Pokey: 0

Serialize object to binary form

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[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;
    [NonSerialized]
    int cacheValue;
}
class MainClass
{
    public static void Main()
    {
        MyElement ele = new MyElement("name");
        Console.WriteLine("Initial value");
        Console.WriteLine("{0}", ele);
        
        // write to binary, read it back
        Stream streamWrite = File.Create("MyElement.bin");
        BinaryFormatter binaryWrite = new BinaryFormatter();
        binaryWrite.Serialize(streamWrite, ele);
        streamWrite.Close();
        
        Stream streamRead = File.OpenRead("MyElement.bin");
        BinaryFormatter binaryRead = new BinaryFormatter();
        MyElement element = (MyElement) binaryRead.Deserialize(streamRead);
        streamRead.Close();
        
        Console.WriteLine("Values after binary serialization");
        Console.WriteLine("{0}", element);
        
    }
}
Initial value
name: 15
Values after binary serialization
name: 0

Specify NonSerialized fields

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[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;
    [NonSerialized]
    int cacheValue;
}
class MainClass
{
    public static void Main()
    {
        MyElement ele = new MyElement("name");
        Console.WriteLine("Initial value");
        Console.WriteLine("{0}", ele);
        
        // write to binary, read it back
        Stream streamWrite = File.Create("MyElement.bin");
        BinaryFormatter binaryWrite = new BinaryFormatter();
        binaryWrite.Serialize(streamWrite, ele);
        streamWrite.Close();
        
        Stream streamRead = File.OpenRead("MyElement.bin");
        BinaryFormatter binaryRead = new BinaryFormatter();
        MyElement element = (MyElement) binaryRead.Deserialize(streamRead);
        streamRead.Close();
        
        Console.WriteLine("Values after binary serialization");
        Console.WriteLine("{0}", element);
        
    }
}
Initial value
name: 15
Values after binary serialization
name: 0