BinaryFormatter BinaryFormatter BinaryFormatter BinaryFormatter Class

Definición

Serializa y deserializa un objeto, o todo un grafo de objetos conectados, en formato binario.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
Herencia
BinaryFormatterBinaryFormatterBinaryFormatterBinaryFormatter
Atributos
Implementaciones

Ejemplos

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

Comentarios

El SoapFormatter y BinaryFormatter clases implementan la IRemotingFormatter interfaz para admitir llamadas a procedimiento remoto (RPC) y el IFormatter interfaz (heredan la IRemotingFormatter) para admitir la serialización de un 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. El SoapFormatter clase también admite RPC con ISoapMessage objetos sin utilizar el IRemotingFormatter funcionalidad.The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

Durante las llamadas RPC, el IRemotingFormatter interfaz permite la especificación de dos gráficos de objetos diferentes: el gráfico de objetos para serializar y un gráfico adicional que contiene una matriz de objetos de encabezado que contienen información acerca de la llamada a función remota (para ejemplo, Id. de transacción o una firma 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).

Llamadas RPC que utilizan el BinaryFormatter independientes en dos partes distintas: llamadas de método, que se envían al servidor con el objeto remoto que contiene el método llamado y respuestas de método, que se envían desde el servidor al cliente con el estado y respuesta información del método llamado.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 la serialización de una llamada al método el primer objeto del gráfico de objetos debe admitir la IMethodCallMessage interfaz.During serialization of a method call the first object of the object graph must support the IMethodCallMessage interface. Para deserializar una llamada al método, utilice el Deserialize método con el HeaderHandler parámetro.To deserialize a method call, use the Deserialize method with the HeaderHandler parameter. La infraestructura de comunicación remota utiliza el HeaderHandler delegado para generar un objeto que admite el ISerializable interfaz.The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. Cuando el BinaryFormatter invoca el HeaderHandler delegado, devuelve el URI del objeto remoto con el método que se llama.When the BinaryFormatter invokes the HeaderHandler delegate, it returns the URI of the remote object with the method that is being called. El primer objeto de gráfico devuelto admite la IMethodCallMessage interfaz.The first object in the graph returned supports the IMethodCallMessage interface.

El procedimiento de serialización de una respuesta de método es idéntico de una llamada al método, salvo el primer objeto del objeto de gráfico debe admitir la IMethodReturnMessage interfaz.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 deserializar una respuesta de método, utilice el DeserializeMethodResponse método.To deserialize a method response, use the DeserializeMethodResponse method. Para ahorrar tiempo, detalles sobre el objeto de autor de llamada no se envían al objeto remoto durante la llamada al método.To save time, details about the caller object are not sent to the remote object during the method call. Estos detalles en su lugar, se obtienen de la llamada al método original, que se pasa a la DeserializeMethodResponse método en el IMethodCallMessage parámetro.These details are instead obtained from the original method call, which is passed to the DeserializeMethodResponse method in the IMethodCallMessage parameter. El primer objeto de gráfico devuelto por la DeserializeMethodResponse método admite la IMethodReturnMessage interfaz.The first object in the graph returned by the DeserializeMethodResponse method supports the IMethodReturnMessage interface.

Importante

Utiliza la serialización binaria para deserializar los datos de confianza puede dar lugar a riesgos de seguridad.Using binary serialization to deserialize untrusted data can lead to security risks. Para obtener más información, vea Data Validation (Validación de datos).For more information, see Data Validation.

Suplentes sin parUnpaired Surrogates

Cualquier carácter suplente no emparejado se pierdan durante la serialización binaria.Any unpaired surrogate characters are lost in binary serialization. Por ejemplo, la siguiente cadena contiene un carácter Unicode de suplente alto (\ud800) entre los dos Test palabras:For example, the following string contains a high surrogate Unicode character (\ud800) in between the two Test words:

Test\ud800Test

Antes de la serialización, la matriz de bytes de la cadena es como sigue:Before serialization, the byte array of the string is as follows:

Valor de la matriz de bytesByte Array Value CarácterCharacter
8484 TT
101101 he
115115 ss
116116 mt
5529655296 \ud800\ud800
8484 TT
101101 he
115115 ss
116116 mt

Después de la deserialización, se pierde el carácter Unicode de suplente alto:After deserialization, the high surrogate Unicode character is lost:

Valor de la matriz de bytesByte Array Value CarácterCharacter
8484 TT
101101 he
115115 ss
116116 mt
8484 TT
101101 he
115115 ss
116116 mt

Constructores

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

Inicializa una nueva instancia de la clase BinaryFormatter con valores predeterminados.Initializes a new instance of the BinaryFormatter class with default values.

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

Inicializa una nueva instancia de la clase BinaryFormatter con el selector suplente y el contexto de secuencia especificados.Initializes a new instance of the BinaryFormatter class with a given surrogate selector and streaming context.

Propiedades

AssemblyFormat AssemblyFormat AssemblyFormat AssemblyFormat

Obtiene o establece el comportamiento del deserializador en lo que respecta a buscar y cargar ensamblados.Gets or sets the behavior of the deserializer with regards to finding and loading assemblies.

Binder Binder Binder Binder

Obtiene o establece un objeto de tipo SerializationBinder que controla el enlace entre un objeto serializado y un tipo.Gets or sets an object of type SerializationBinder that controls the binding of a serialized object to a type.

Context Context Context Context

Obtiene o establece StreamingContext para este formateador.Gets or sets the StreamingContext for this formatter.

FilterLevel FilterLevel FilterLevel FilterLevel

Obtiene o establece el TypeFilterLevel de la deserialización automática que realiza BinaryFormatter.Gets or sets the TypeFilterLevel of automatic deserialization the BinaryFormatter performs.

SurrogateSelector SurrogateSelector SurrogateSelector SurrogateSelector

Obtiene o establece un ISurrogateSelector que controla la sustitución de tipos durante la serialización y la deserialización.Gets or sets a ISurrogateSelector that controls type substitution during serialization and deserialization.

TypeFormat TypeFormat TypeFormat TypeFormat

Obtiene o establece el formato en que se distribuyen las descripciones de tipos en la secuencia serializada.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)

Deserializa la secuencia especificada en un gráfico de objetos.Deserializes the specified stream into an object graph.

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

Deserializa la secuencia especificada en un gráfico de objetos.Deserializes the specified stream into an object graph. El HeaderHandler suministrado controla los encabezados de dicha secuencia.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)

Deserializa una respuesta a una llamada de método remota a partir del Stream proporcionado.Deserializes a response to a remote method call from the provided Stream.

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

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

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

Sirve como la función hash predeterminada.Serves as the default hash function.

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

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

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

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

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

Serializa el objeto, o gráfico de objetos con el objeto superior (raíz) especificado, en la secuencia indicada.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 el objeto, o gráfico de objetos con el objeto superior (raíz) especificado, en la secuencia indicada adjuntado los encabezados proporcionados.Serializes the object, or graph of objects with the specified top (root), to the given stream attaching the provided headers.

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

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

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

Deserializa la secuencia especificada en un gráfico de objetos.Deserializes the specified stream into an object graph. El HeaderHandler suministrado controla los encabezados de dicha secuencia.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)

Deserializa una respuesta a una llamada de método remota a partir del Stream proporcionado.Deserializes a response to a remote method call from the provided Stream.

Se aplica a