BinaryFormatter Clase

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
BinaryFormatter
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

Las SoapFormatter clases BinaryFormatter y implementan IRemotingFormatter la interfaz para admitir llamadas a procedimientos remotos (RPC) IFormatter y la interfaz (heredada por 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. La SoapFormatter clase también admite RPC con ISoapMessage objetos, sin usar la IRemotingFormatter funcionalidad.The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

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

RPC que usan la BinaryFormatter independiente 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 la 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 IMethodCallMessage debe ser compatible con la 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, use Deserialize el método con HeaderHandler el parámetro.To deserialize a method call, use the Deserialize method with the HeaderHandler parameter. La infraestructura de comunicación remota HeaderHandler usa el delegado para generar un objeto que ISerializable admita la interfaz.The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. Cuando invoca el HeaderHandler delegado, devuelve el URI del objeto remoto con el método al que se está llamando. BinaryFormatterWhen the BinaryFormatter invokes the HeaderHandler delegate, it returns the URI of the remote object with the method that is being called. El primer objeto del gráfico devuelto es compatible IMethodCallMessage con la 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 al de una llamada al método, salvo que el primer objeto del gráfico de objetos IMethodReturnMessage debe ser compatible con la 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, use DeserializeMethodResponse el método.To deserialize a method response, use the DeserializeMethodResponse method. Para ahorrar tiempo, los detalles sobre el objeto de llamador 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. En su lugar, estos detalles se obtienen de la llamada al método original, que se DeserializeMethodResponse pasa al método IMethodCallMessage en el 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 del gráfico devuelto por el DeserializeMethodResponse método admite la IMethodReturnMessage interfaz.The first object in the graph returned by the DeserializeMethodResponse method supports the IMethodReturnMessage interface.

Importante

El uso de la serialización binaria para deserializar los datos que no son de confianza puede provocar 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 no emparejadosUnpaired Surrogates

Los caracteres suplentes no emparejados se pierden en la serialización binaria.Any unpaired surrogate characters are lost in binary serialization. Por ejemplo, la siguiente cadena contiene un carácter (\ud800Unicode suplente alto) entre las 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 la siguiente:Before serialization, the byte array of the string is as follows:

Valor de 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 suplente alto:After deserialization, the high surrogate Unicode character is lost:

Valor de 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()

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)

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

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

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

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

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

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

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)

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

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)

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)

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

(Heredado de Object)
GetHashCode()

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

(Heredado de Object)
GetType()

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

(Heredado de Object)
MemberwiseClone()

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

(Heredado de 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[])

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()

Devuelve un valor de tipo string que representa el objeto actual.Returns a string that represents the current object.

(Heredado de Object)
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)

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