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::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
- 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
Advertencia
BinaryFormatter
no es seguro y no se puede proteger.BinaryFormatter
is insecure and can't be made secure. Para obtener más información, vea la Guía de seguridad BinaryFormatter.For more information, see the BinaryFormatter security guide.
Las SoapFormatter BinaryFormatter clases y implementan la IRemotingFormatter interfaz para admitir llamadas a procedimientos remotos (RPC) y la IFormatter 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, la IRemotingFormatter 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 (por ejemplo, un identificador 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).
Las 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 la información de estado y de respuesta 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 ser compatible con 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, use 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 usa el HeaderHandler delegado para generar un objeto que admita la ISerializable interfaz.The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. Cuando BinaryFormatter invoca el HeaderHandler delegado, devuelve el URI del objeto remoto con el método al que se está llamando.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 del gráfico devuelto es compatible con 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 al de una llamada al método, salvo que el primer objeto del gráfico de objetos debe ser compatible con 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, use el DeserializeMethodResponse 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 pasa al 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 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 validación de datos y la guía de seguridad BinaryFormatter.For more information, see Data Validation and the BinaryFormatter security guide.
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 Unicode suplente alto (\ud800
) 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 | tt |
5529655296 | \ud800\ud800 |
8484 | TT |
101101 | he |
115115 | ss |
116116 | tt |
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 | tt |
8484 | TT |
101101 | he |
115115 | ss |
116116 | tt |
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 |
(No seguro) Obtiene o establece un objeto de tipo SerializationBinder que controla el enlace entre un objeto serializado a un tipo.(Insecure) 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) |
Obsoleto.
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 que el objeto actual.Determines whether the specified object is equal to the current object. (Heredado de Object) |
GetHashCode() |
Sirve como la 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) |
Obsoleto.
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 una cadena 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. |