BinaryFormatter BinaryFormatter BinaryFormatter BinaryFormatter Class

Definição

Serializa e desserializa um objeto ou um grafo inteiro de objetos conectados, em formato binário.Serializes and deserializes an object, or an entire graph of connected objects, in binary format.

public ref class BinaryFormatter sealed : System::Runtime::Remoting::Messaging::IRemotingFormatter
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class BinaryFormatter : System.Runtime.Remoting.Messaging.IRemotingFormatter
type BinaryFormatter = class
    interface IRemotingFormatter
    interface IFormatter
Public NotInheritable Class BinaryFormatter
Implements IRemotingFormatter
Herança
BinaryFormatterBinaryFormatterBinaryFormatterBinaryFormatter
Atributos
Implementações

Exemplos

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

Comentários

O SoapFormatter e BinaryFormatter classes implementam a IRemotingFormatter interface para oferecer suporte a chamadas de procedimento remoto (RPCs) e o IFormatter interface (herdada pelo IRemotingFormatter) para dar suporte à serialização de um gráfico de objetos.The SoapFormatter and BinaryFormatter classes implement the IRemotingFormatter interface to support remote procedure calls (RPCs), and the IFormatter interface (inherited by the IRemotingFormatter) to support serialization of a graph of objects. O SoapFormatter classe também dá suporte a RPCs com ISoapMessage objetos, sem usar o IRemotingFormatter funcionalidade.The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

Durante a RPCs, o IRemotingFormatter interface permite a especificação de dois grafos de objeto separado: o grafo de objetos a serem serializados e um gráfico adicional que contém uma matriz de objetos de cabeçalho que transmitem informações sobre a chamada de função remota (para exemplo, ID da transação ou uma assinatura de método).During RPCs, the IRemotingFormatter interface allows the specification of two separate object graphs: the graph of objects to serialize, and an additional graph that contains an array of header objects that convey information about the remote function call (for example, transaction ID or a method signature).

RPCs que usam o BinaryFormatter separados em duas partes distintas: chamadas de método, que são enviadas para o servidor com o objeto remoto que contém o método chamado e as respostas do método, que são enviadas ao cliente com o status do servidor e resposta informações do método chamado.RPCs that use the BinaryFormatter separate into two distinct parts: method calls, which are sent to the server with the remote object that contains the method called, and method responses, which are sent from the server to the client with the status and response information from the called method.

Durante a serialização de uma chamada de método ao primeiro objeto do grafo de objeto deve dar suporte a IMethodCallMessage interface.During serialization of a method call the first object of the object graph must support the IMethodCallMessage interface. Para desserializar uma chamada de método, use o Deserialize método com o HeaderHandler parâmetro.To deserialize a method call, use the Deserialize method with the HeaderHandler parameter. A infraestrutura de comunicação remota usa o HeaderHandler delegado para produzir um objeto que dá suporte a ISerializable interface.The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. Quando o BinaryFormatter invoca o HeaderHandler representante, ele retorna o URI do objeto remoto com o método que está sendo chamado.When the BinaryFormatter invokes the HeaderHandler delegate, it returns the URI of the remote object with the method that is being called. O primeiro objeto no grafo retornado dá suporte a IMethodCallMessage interface.The first object in the graph returned supports the IMethodCallMessage interface.

O procedimento de serialização para uma resposta do método é idêntico de uma chamada de método, exceto o primeiro objeto do objeto de gráfico deve oferecer suporte a IMethodReturnMessage interface.The serialization procedure for a method response is identical to that of a method call, except the first object of the object graph must support the IMethodReturnMessage interface. Para desserializar uma resposta de método, use o DeserializeMethodResponse método.To deserialize a method response, use the DeserializeMethodResponse method. Para economizar tempo, detalhes sobre o objeto chamador não são enviados para o objeto remoto durante a chamada de método.To save time, details about the caller object are not sent to the remote object during the method call. Em vez disso, esses detalhes são obtidos de chamada do método original, que é passada para o DeserializeMethodResponse método no IMethodCallMessage parâmetro.These details are instead obtained from the original method call, which is passed to the DeserializeMethodResponse method in the IMethodCallMessage parameter. O primeiro objeto do gráfico retornado pela DeserializeMethodResponse método suporta a IMethodReturnMessage interface.The first object in the graph returned by the DeserializeMethodResponse method supports the IMethodReturnMessage interface.

Importante

Usar a serialização binária para desserializar dados não confiáveis pode levar a riscos de segurança.Using binary serialization to deserialize untrusted data can lead to security risks. Para obter mais informações, confira Validação de dados.For more information, see Data Validation.

Substitutos não emparelhadosUnpaired Surrogates

Caracteres substitutos não emparelhados são perdidos na serialização binária.Any unpaired surrogate characters are lost in binary serialization. Por exemplo, a seguinte cadeia de caracteres contém um caractere Unicode de substituto alto (\ud800) entre esses dois Test palavras:For example, the following string contains a high surrogate Unicode character (\ud800) in between the two Test words:

Test\ud800Test

Antes da serialização, a matriz de bytes da cadeia de caracteres é o seguinte:Before serialization, the byte array of the string is as follows:

Valor de matriz de bytesByte Array Value CaractereCharacter
8484 TT
101101 ee
115115 ss
116116 tt
5529655296 \ud800\ud800
8484 TT
101101 ee
115115 ss
116116 tt

Após a desserialização, o caractere Unicode de substituto alto será perdido:After deserialization, the high surrogate Unicode character is lost:

Valor de matriz de bytesByte Array Value CaractereCharacter
8484 TT
101101 ee
115115 ss
116116 tt
8484 TT
101101 ee
115115 ss
116116 tt

Construtores

BinaryFormatter() BinaryFormatter() BinaryFormatter() BinaryFormatter()

Inicializa uma nova instância da classe BinaryFormatter com valores padrão.Initializes a new instance of the BinaryFormatter class with default values.

BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext) BinaryFormatter(ISurrogateSelector, StreamingContext)

Inicializa uma nova instância de BinaryFormatter classe com um seletor substituto determinado e o contexto de streaming.Initializes a new instance of the BinaryFormatter class with a given surrogate selector and streaming context.

Propriedades

AssemblyFormat AssemblyFormat AssemblyFormat AssemblyFormat

Obtém ou define o comportamento do desserializador em relação a encontrar e carregar assemblies.Gets or sets the behavior of the deserializer with regards to finding and loading assemblies.

Binder Binder Binder Binder

Obtém ou define um objeto do tipo SerializationBinder que controla a associação de um objeto serializado a um tipo.Gets or sets an object of type SerializationBinder that controls the binding of a serialized object to a type.

Context Context Context Context

Obtém ou define o StreamingContext para esse formatador.Gets or sets the StreamingContext for this formatter.

FilterLevel FilterLevel FilterLevel FilterLevel

Obtém ou define o TypeFilterLevel de desserialização automática que o BinaryFormatter executa.Gets or sets the TypeFilterLevel of automatic deserialization the BinaryFormatter performs.

SurrogateSelector SurrogateSelector SurrogateSelector SurrogateSelector

Obtém ou define um ISurrogateSelector que controla a substituição de tipo durante a serialização e desserialização.Gets or sets a ISurrogateSelector that controls type substitution during serialization and deserialization.

TypeFormat TypeFormat TypeFormat TypeFormat

Obtém ou define o formato no qual as descrições de tipo são apresentadas no fluxo serializado.Gets or sets the format in which type descriptions are laid out in the serialized stream.

Métodos

Deserialize(Stream) Deserialize(Stream) Deserialize(Stream) Deserialize(Stream)

Desserializa o fluxo especificado em um grafo de objeto.Deserializes the specified stream into an object graph.

Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler) Deserialize(Stream, HeaderHandler)

Desserializa o fluxo especificado em um grafo de objeto.Deserializes the specified stream into an object graph. O HeaderHandler fornecido manipula qualquer cabeçalho nesse fluxo.The provided HeaderHandler handles any headers in that stream.

DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) DeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

Desserializa uma resposta a uma chamada de método remoto do Stream fornecido.Deserializes a response to a remote method call from the provided Stream.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object)

Serializa o objeto ou grafo de objetos com o topo (raiz) especificado para o fluxo especificado.Serializes the object, or graph of objects with the specified top (root), to the given stream.

Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[]) Serialize(Stream, Object, Header[])

Serializa o objeto ou o grafo de objetos com o topo (raiz) especificado para o fluxo determinado, anexando os cabeçalhos fornecidos.Serializes the object, or graph of objects with the specified top (root), to the given stream attaching the provided headers.

ToString() ToString() ToString() ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Inherited from Object)
UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler) UnsafeDeserialize(Stream, HeaderHandler)

Desserializa o fluxo especificado em um grafo de objeto.Deserializes the specified stream into an object graph. O HeaderHandler fornecido manipula qualquer cabeçalho nesse fluxo.The provided HeaderHandler handles any headers in that stream.

UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage) UnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

Desserializa uma resposta a uma chamada de método remoto do Stream fornecido.Deserializes a response to a remote method call from the provided Stream.

Aplica-se a