BinaryFormatter Class

 

Serializes and deserializes an object, or an entire graph of connected objects, in binary format.

Namespace:   System.Runtime.Serialization.Formatters.Binary
Assembly:  mscorlib (in mscorlib.dll)

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

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

NameDescription
System_CAPS_pubmethodBinaryFormatter()

Initializes a new instance of the BinaryFormatter class with default values.

System_CAPS_pubmethodBinaryFormatter(ISurrogateSelector^, StreamingContext)

Initializes a new instance of the BinaryFormatter class with a given surrogate selector and streaming context.

NameDescription
System_CAPS_pubpropertyAssemblyFormat

Gets or sets the behavior of the deserializer with regards to finding and loading assemblies.

System_CAPS_pubpropertyBinder

Gets or sets an object of type SerializationBinder that controls the binding of a serialized object to a type.

System_CAPS_pubpropertyContext

Gets or sets the StreamingContext for this formatter.

System_CAPS_pubpropertyFilterLevel

Gets or sets the TypeFilterLevel of automatic deserialization the BinaryFormatter performs.

System_CAPS_pubpropertySurrogateSelector

Gets or sets a ISurrogateSelector that controls type substitution during serialization and deserialization.

System_CAPS_pubpropertyTypeFormat

Gets or sets the format in which type descriptions are laid out in the serialized stream.

NameDescription
System_CAPS_pubmethodDeserialize(Stream^)

Deserializes the specified stream into an object graph.

System_CAPS_pubmethodDeserialize(Stream^, HeaderHandler^)

Deserializes the specified stream into an object graph. The provided HeaderHandler handles any headers in that stream.

System_CAPS_pubmethodDeserializeMethodResponse(Stream^, HeaderHandler^, IMethodCallMessage^)

Deserializes a response to a remote method call from the provided Stream.

System_CAPS_pubmethodEquals(Object^)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodSerialize(Stream^, Object^)

Serializes the object, or graph of objects with the specified top (root), to the given stream.

System_CAPS_pubmethodSerialize(Stream^, Object^, array<Header^>^)

Serializes the object, or graph of objects with the specified top (root), to the given stream attaching the provided headers.

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_pubmethodUnsafeDeserialize(Stream^, HeaderHandler^)

Deserializes the specified stream into an object graph. The provided HeaderHandler handles any headers in that stream.

System_CAPS_pubmethodUnsafeDeserializeMethodResponse(Stream^, HeaderHandler^, IMethodCallMessage^)

Deserializes a response to a remote method call from the provided Stream.

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. The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.

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

During serialization of a method call the first object of the object graph must support the IMethodCallMessage interface. To deserialize a method call, use the Deserialize method with the HeaderHandler parameter. The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. When the BinaryFormatter invokes the 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 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 IMethodReturnMessage interface. To deserialize a method response, use the DeserializeMethodResponse 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 DeserializeMethodResponse method in the IMethodCallMessage parameter. The first object in the graph returned by the DeserializeMethodResponse method supports the IMethodReturnMessage interface.

System_CAPS_security Security Note

Using binary serialization to deserialize untrusted data can lead to security risks. For more information, see Untrusted Data Security Risks.

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

.NET Framework
Available since 1.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show: