BinaryFormatter 类

定义

以二进制格式序列化和反序列化对象或连接对象的整个图形。

public ref class BinaryFormatter sealed : System::Runtime::Serialization::IFormatter
public ref class BinaryFormatter sealed : System::Runtime::Remoting::Messaging::IRemotingFormatter
public sealed class BinaryFormatter : System.Runtime.Serialization.IFormatter
public sealed class BinaryFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class BinaryFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter
type BinaryFormatter = class
    interface IFormatter
type BinaryFormatter = class
    interface IRemotingFormatter
    interface IFormatter
[<System.Runtime.InteropServices.ComVisible(true)>]
type BinaryFormatter = class
    interface IRemotingFormatter
    interface IFormatter
Public NotInheritable Class BinaryFormatter
Implements IFormatter
Public NotInheritable Class BinaryFormatter
Implements IRemotingFormatter
继承
BinaryFormatter
属性
实现

示例

using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Runtime::Serialization;
ref class App
{
public:
   static void Serialize()
   {
      
      // Create a hashtable of values that will eventually be serialized.
      Hashtable^ addresses = gcnew Hashtable;
      addresses->Add( "Jeff", "123 Main Street, Redmond, WA 98052" );
      addresses->Add( "Fred", "987 Pine Road, Phila., PA 19116" );
      addresses->Add( "Mary", "PO Box 112233, Palo Alto, CA 94301" );
      
      // To serialize the hashtable (and its keys/values),  
      // you must first open a stream for writing. 
      // In this case we will use a file stream.
      FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Create );
      
      // Construct a BinaryFormatter and use it to serialize the data to the stream.
      BinaryFormatter^ formatter = gcnew BinaryFormatter;
      try
      {
         formatter->Serialize( fs, addresses );
      }
      catch ( SerializationException^ e ) 
      {
         Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );
         throw;
      }
      finally
      {
         fs->Close();
      }

   }

   static void Deserialize()
   {
      
      // Declare the hashtable reference.
      Hashtable^ addresses = nullptr;
      
      // Open the file containing the data that we want to deserialize.
      FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Open );
      try
      {
         BinaryFormatter^ formatter = gcnew BinaryFormatter;
         
         // Deserialize the hashtable from the file and 
         // assign the reference to our local variable.
         addresses = dynamic_cast<Hashtable^>(formatter->Deserialize( fs ));
      }
      catch ( SerializationException^ e ) 
      {
         Console::WriteLine( "Failed to deserialize. Reason: {0}", e->Message );
         throw;
      }
      finally
      {
         fs->Close();
      }

      
      // To prove that the table deserialized correctly, display the keys/values.
      IEnumerator^ myEnum = addresses->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         DictionaryEntry ^ de = safe_cast<DictionaryEntry ^>(myEnum->Current);
         Console::WriteLine( " {0} lives at {1}.", de->Key, de->Value );
      }
   }

};


[STAThread]
int main()
{
   App::Serialize();
   App::Deserialize();
   return 0;
}
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

public class App
{
    [STAThread]
    static void Main()
    {
        Serialize();
        Deserialize();
    }

    static void Serialize()
    {
        // Create a hashtable of values that will eventually be serialized.
        Hashtable addresses = new Hashtable();
        addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
        addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
        addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");

        // To serialize the hashtable and its key/value pairs,
        // you must first open a stream for writing.
        // In this case, use a file stream.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

        // Construct a BinaryFormatter and use it to serialize the data to the stream.
        BinaryFormatter formatter = new BinaryFormatter();
        try
        {
            formatter.Serialize(fs, addresses);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }
    }

    static void Deserialize()
    {
        // Declare the hashtable reference.
        Hashtable addresses  = null;

        // Open the file containing the data that you want to deserialize.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
        try
        {
            BinaryFormatter formatter = new BinaryFormatter();

            // Deserialize the hashtable from the file and
            // assign the reference to the local variable.
            addresses = (Hashtable) formatter.Deserialize(fs);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }

        // To prove that the table deserialized correctly,
        // display the key/value pairs.
        foreach (DictionaryEntry de in addresses)
        {
            Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
        }
    }
}
Imports System.IO
Imports System.Collections
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization


Module App

    Sub Main()
        Serialize()
        Deserialize()
    End Sub

    Sub Serialize()

        ' Create a hashtable of values that will eventually be serialized.
        Dim addresses As New Hashtable
        addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052")
        addresses.Add("Fred", "987 Pine Road, Phila., PA 19116")
        addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301")

        ' To serialize the hashtable (and its key/value pairs),  
        ' you must first open a stream for writing. 
        ' In this case, use a file stream.
        Dim fs As New FileStream("DataFile.dat", FileMode.Create)

        ' Construct a BinaryFormatter and use it to serialize the data to the stream.
        Dim formatter As New BinaryFormatter
        Try
            formatter.Serialize(fs, addresses)
        Catch e As SerializationException
            Console.WriteLine("Failed to serialize. Reason: " & e.Message)
            Throw
        Finally
            fs.Close()
        End Try
    End Sub



    Sub Deserialize()
        ' Declare the hashtable reference.
        Dim addresses As Hashtable = Nothing

        ' Open the file containing the data that you want to deserialize.
        Dim fs As New FileStream("DataFile.dat", FileMode.Open)
        Try
            Dim formatter As New BinaryFormatter

            ' Deserialize the hashtable from the file and 
            ' assign the reference to the local variable.
            addresses = DirectCast(formatter.Deserialize(fs), Hashtable)
        Catch e As SerializationException
            Console.WriteLine("Failed to deserialize. Reason: " & e.Message)
            Throw
        Finally
            fs.Close()
        End Try

        ' To prove that the table deserialized correctly, 
        ' display the key/value pairs.
        Dim de As DictionaryEntry
        For Each de In addresses
            Console.WriteLine("{0} lives at {1}.", de.Key, de.Value)
        Next
    End Sub
End Module

注解

警告

BinaryFormatter 是不安全的,无法使其安全。 有关详细信息,请参阅 BinaryFormatter security guide (安全指南)。

这些 SoapFormatterBinaryFormatter 类实现 IRemotingFormatter 接口以支持远程过程调用 (RPC) , IFormatter 以及) 继承的 IRemotingFormatter 接口 (,以支持对象的图形序列化。 该 SoapFormatter 类还支持具有 ISoapMessage 对象的 RPC,而无需使用 IRemotingFormatter 该功能。

在 RPC 期间, IRemotingFormatter 接口允许规范两个单独的对象图:要序列化的对象图,以及一个包含一组标头对象的标头对象数组,这些标头对象传达有关远程函数 (调用的信息,例如事务 ID 或方法签名) 。

使用 BinaryFormatter 单独部分的RPC分为两个不同的部分:方法调用,该方法调用将发送到包含调用方法的远程对象的服务器,以及从服务器发送到具有调用方法的状态和响应信息的客户端的方法响应。

在方法序列化期间,调用对象图的第一个对象必须支持 IMethodCallMessage 接口。 若要反序列化方法调用,请使用带DeserializeHeaderHandler参数的方法。 远程处理基础结构使用 HeaderHandler 委托生成支持 ISerializable 接口的对象。 BinaryFormatter调用HeaderHandler委托时,它会使用调用的方法返回远程对象的 URI。 返回的图形中的第一个对象支持 IMethodCallMessage 接口。

方法响应的序列化过程与方法调用的序列化过程相同,但对象图的第一个对象必须支持 IMethodReturnMessage 接口。 若要反序列化方法响应,请使用 DeserializeMethodResponse 该方法。 为了节省时间,方法调用期间不会将有关调用方对象的详细信息发送到远程对象。 这些详细信息是从原始方法调用获取的,该调用将传递给 DeserializeMethodResponse 参数中的 IMethodCallMessage 方法。 方法返回 DeserializeMethodResponse 的图形中的第一个对象支持 IMethodReturnMessage 接口。

重要

使用二进制序列化反序列化不受信任的数据可能会导致安全风险。 有关详细信息,请参阅 数据验证BinaryFormatter 安全指南

未付代理项

任何未配对代理项字符在二进制序列化中都会丢失。 例如,以下字符串包含两Test个单词之间的高代理项 Unicode 字符(\ud800) :

Test\ud800Test

序列化之前,字符串的字节数组如下所示:

字节数组值 字符
84 T
101 e
115 s
116 T
55296 \ud800
84 T
101 e
115 s
116 T

反序列化后,高代理项 Unicode 字符丢失:

字节数组值 字符
84 T
101 e
115 s
116 T
84 T
101 e
115 s
116 T

构造函数

BinaryFormatter()

使用默认值初始化 BinaryFormatter 类的新实例。

BinaryFormatter(ISurrogateSelector, StreamingContext)

使用给定的代理项选择器和流上下文来初始化 BinaryFormatter 类的新实例。

属性

AssemblyFormat

获取或设置与查找加集有关的反序列化器行为。

Binder

(不安全)获取或设置控制将序列化对象绑定到类型的 SerializationBinder 类型的对象。

Context

获取或设置此格式化程序的 StreamingContext

FilterLevel

获取或设置 TypeFilterLevel 所执行的自动反序列化的 BinaryFormatter

SurrogateSelector

获取或设置控制序列化和反序列化过程的类型替换的 ISurrogateSelector.

TypeFormat

获取或设置类型说明在序列化流中的布局格式。

方法

Deserialize(Stream)
已过时。

将指定的流反序列化为对象图形。

Deserialize(Stream, HeaderHandler)

将指定的流反序列化为对象图形。 所提供的 HeaderHandler 处理该流中的任何标题。

DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

将对远程方法调用的响应从所提供的 Stream 进行反序列化。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
Serialize(Stream, Object)
已过时。

将对象或具有指定顶级(根)的对象图形序列化为给定流。

Serialize(Stream, Object, Header[])

将对象或具有指定顶级(根)的对象图形序列化为附加所提供标题的给定流。

ToString()

返回表示当前对象的字符串。

(继承自 Object)
UnsafeDeserialize(Stream, HeaderHandler)

将指定的流反序列化为对象图形。 所提供的 HeaderHandler 处理该流中的任何标题。

UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

将对远程方法调用的响应从所提供的 Stream 进行反序列化。

适用于