BinaryFormatter Class

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

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

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

'Declaration
<ComVisibleAttribute(True)> _
Public NotInheritable Class BinaryFormatter _
	Implements IRemotingFormatter, IFormatter

The BinaryFormatter type exposes the following members.

  NameDescription
Public methodBinaryFormatterInitializes a new instance of the BinaryFormatter class with default values.
Public methodBinaryFormatter(ISurrogateSelector, StreamingContext)Initializes a new instance of the BinaryFormatter class with a given surrogate selector and streaming context.
Top

  NameDescription
Public propertyAssemblyFormatGets or sets the behavior of the deserializer with regards to finding and loading assemblies.
Public propertyBinderGets or sets an object of type SerializationBinder that controls the binding of a serialized object to a type.
Public propertyContextGets or sets the StreamingContext for this formatter.
Public propertyFilterLevelGets or sets the TypeFilterLevel of automatic deserialization the BinaryFormatter performs.
Public propertySurrogateSelectorGets or sets a ISurrogateSelector that controls type substitution during serialization and deserialization.
Public propertyTypeFormatGets or sets the format in which type descriptions are laid out in the serialized stream.
Top

  NameDescription
Public methodDeserialize(Stream)Deserializes the specified stream into an object graph.
Public methodDeserialize(Stream, HeaderHandler)Deserializes the specified stream into an object graph. The provided HeaderHandler handles any headers in that stream.
Public methodDeserializeMethodResponseDeserializes a response to a remote method call from the provided Stream.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSerialize(Stream, Object)Serializes the object, or graph of objects with the specified top (root), to the given stream.
Public methodSerialize(Stream, Object, Header())Serializes the object, or graph of objects with the specified top (root), to the given stream attaching the provided headers.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodUnsafeDeserializeDeserializes the specified stream into an object graph. The provided HeaderHandler handles any headers in that stream.
Public methodUnsafeDeserializeMethodResponseDeserializes a response to a remote method call from the provided Stream.
Top

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.

Unpaired Surrogates

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

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

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft