Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase BinaryFormatter

 

Serializa y deserializa un objeto, o todo un grafo de objetos conectados, en formato binario.

Espacio de nombres:   System.Runtime.Serialization.Formatters.Binary
Ensamblado:  mscorlib (en mscorlib.dll)

System.Object
  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

[ComVisibleAttribute(true)]
public sealed class BinaryFormatter : IRemotingFormatter, IFormatter

NombreDescripción
System_CAPS_pubmethodBinaryFormatter()

Inicializa una nueva instancia de la clase BinaryFormatter con valores predeterminados.

System_CAPS_pubmethodBinaryFormatter(ISurrogateSelector, StreamingContext)

Inicializa una nueva instancia de la BinaryFormatter clase con un selector suplente y el contexto de transmisión por secuencias.

NombreDescripción
System_CAPS_pubpropertyAssemblyFormat

Obtiene o establece el comportamiento del deserializador en lo que respecta a buscar y cargar los ensamblados.

System_CAPS_pubpropertyBinder

Obtiene o establece un objeto del tipo SerializationBinder que controla el enlace entre un objeto serializado a un tipo.

System_CAPS_pubpropertyContext

Obtiene o establece el StreamingContext para este formateador.

System_CAPS_pubpropertyFilterLevel

Obtiene o establece la TypeFilterLevel de deserialización automática la BinaryFormatter realiza.

System_CAPS_pubpropertySurrogateSelector

Obtiene o establece un ISurrogateSelector que controla la sustitución durante la serialización y deserialización de tipos.

System_CAPS_pubpropertyTypeFormat

Obtiene o establece el formato en el que se distribuyen las descripciones de tipo en la secuencia serializada.

NombreDescripción
System_CAPS_pubmethodDeserialize(Stream)

Deserializa la secuencia especificada en un gráfico de objetos.

System_CAPS_pubmethodDeserialize(Stream, HeaderHandler)

Deserializa la secuencia especificada en un gráfico de objetos. Proporcionado HeaderHandler controla los encabezados de dicha secuencia.

System_CAPS_pubmethodDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

Deserializa una respuesta a una llamada de método remoto proporcionado Stream.

System_CAPS_pubmethodEquals(Object)

Determina si el objeto especificado es igual al objeto actual.(Heredado de Object).

System_CAPS_pubmethodGetHashCode()

Sirve como la función hash predeterminada.(Heredado de Object).

System_CAPS_pubmethodGetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_pubmethodSerialize(Stream, Object)

Serializa el objeto o un gráfico de objetos con el nivel superior (raíz), en la secuencia dada.

System_CAPS_pubmethodSerialize(Stream, Object, Header[])

Serializa el objeto o un gráfico de objetos con el nivel superior (raíz), en la secuencia dada, adjuntando los encabezados proporcionados.

System_CAPS_pubmethodToString()

Devuelve una cadena que representa al objeto actual. (Heredado de Object).

System_CAPS_pubmethodUnsafeDeserialize(Stream, HeaderHandler)

Deserializa la secuencia especificada en un gráfico de objetos. Proporcionado HeaderHandler controla los encabezados de dicha secuencia.

System_CAPS_pubmethodUnsafeDeserializeMethodResponse(Stream, HeaderHandler, IMethodCallMessage)

Deserializa una respuesta a una llamada de método remoto proporcionado Stream.

The T:System.Runtime.Serialization.Formatters.Soap.SoapFormatter and T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter classes implement the T:System.Runtime.Remoting.Messaging.IRemotingFormatter interface to support remote procedure calls (RPCs), and the T:System.Runtime.Serialization.IFormatter interface (inherited by the T:System.Runtime.Remoting.Messaging.IRemotingFormatter) to support serialization of a graph of objects. The T:System.Runtime.Serialization.Formatters.Soap.SoapFormatter class also supports RPCs with T:System.Runtime.Serialization.Formatters.ISoapMessage objects, without using the T:System.Runtime.Remoting.Messaging.IRemotingFormatter functionality.

During RPCs, the T:System.Runtime.Remoting.Messaging.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 that use the T:System.Runtime.Serialization.Formatters.Binary.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.

During serialization of a method call the first object of the object graph must support the T:System.Runtime.Remoting.Messaging.IMethodCallMessage interface. To deserialize a method call, use the M:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(System.IO.Stream) method with the T:System.Runtime.Remoting.Messaging.HeaderHandler parameter. The remoting infrastructure uses the T:System.Runtime.Remoting.Messaging.HeaderHandler delegate to produce an object that supports the T:System.Runtime.Serialization.ISerializable interface. When the T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter invokes the T:System.Runtime.Remoting.Messaging.HeaderHandler delegate, it returns the URI of the remote object with the method that is being called. The first object in the graph returned supports the T:System.Runtime.Remoting.Messaging.IMethodCallMessage 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 T:System.Runtime.Remoting.Messaging.IMethodReturnMessage interface. To deserialize a method response, use the M:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.DeserializeMethodResponse(System.IO.Stream,System.Runtime.Remoting.Messaging.HeaderHandler,System.Runtime.Remoting.Messaging.IMethodCallMessage) method. To save time, details about the caller object are not sent to the remote object during the method call. These details are instead obtained from the original method call, which is passed to the M:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.DeserializeMethodResponse(System.IO.Stream,System.Runtime.Remoting.Messaging.HeaderHandler,System.Runtime.Remoting.Messaging.IMethodCallMessage) method in the T:System.Runtime.Remoting.Messaging.IMethodCallMessage parameter. The first object in the graph returned by the M:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.DeserializeMethodResponse(System.IO.Stream,System.Runtime.Remoting.Messaging.HeaderHandler,System.Runtime.Remoting.Messaging.IMethodCallMessage) method supports the T:System.Runtime.Remoting.Messaging.IMethodReturnMessage interface.

System_CAPS_security Seguridad Nota

Using binary serialization to deserialize untrusted data can lead to security risks. For more information, see Untrusted Data Security Riskshttp://go.microsoft.com/fwlink/?LinkId=330378.

Any unpaired surrogate characters are lost in binary serialization. For example, the following string contains a high surrogate Unicode character (\ud800) in between the two Test words:

Test\ud800Test

Before serialization, the byte array of the string is as follows:

Byte Array Value

Character

84

T

101

e

115

s

116

t

55296

\ud800

84

T

101

e

115

s

116

t

After deserialization, the high surrogate Unicode character is lost:

Byte Array Value

Character

84

T

101

e

115

s

116

t

84

T

101

e

115

s

116

t

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);
        }
    }
}

.NET Framework
Disponible desde 1.1

Cualquier miembro ( Compartido en Visual Basic) estático público de este tipo es seguro para subprocesos. No se garantiza que los miembros de instancia sean seguros para subprocesos.

Volver al principio
Mostrar: