BinarySerializationFormatter Class
Serializes and deserializes objects in binary format.
Namespace: KGySoft.Serialization.BinaryAssembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 7.2.0
public sealed class BinarySerializationFormatter : IFormatter
Public NotInheritable Class BinarySerializationFormatter
Implements IFormatter
public ref class BinarySerializationFormatter sealed : IFormatter
[<SealedAttribute>]
type BinarySerializationFormatter =
class
interface IFormatter
end
- Inheritance
- Object BinarySerializationFormatter
- Implements
- IFormatter
The fundamental goal of binary serialization is to store the bitwise content of an object, hence in general case it relies on
field values (including private ones), which can change from version to version. Therefore, binary serialization is recommended only for in-process purposes,
such as deep cloning or undo/redo, etc. If it is known that a type will be deserialized in another environment and it can be completely restored by its public members,
then a text-based serialization (see also
XmlSerializer) can be a better choice.
Do not use binary serialization if the serialization stream may come from an untrusted source (eg. remote service, file or database).
If you still need to do so (eg. due to compatibility), then it is highly recommended to enable the SafeMode option, which prevents
loading assemblies during the deserialization as well as instantiating non-serializable types, and guards against some attacks that may cause OutOfMemoryException.
When using SafeMode you must preload every assembly referred by the serialization stream.
Please note though that even some system types can be dangerous. In the .NET Framework there are some serializable types in the fundamental core assemblies that
can be exploited for several attacks (causing unresponsiveness, StackOverflowException or even files to be deleted). Starting with .NET Core these types are not
serializable anymore and some of them have been moved to separate NuGet packages anyway, but the BinaryFormatter in the .NET Framework is still vulnerable against such attacks.
When using the SafeMode flag, the BinarySerializationFormatter is protected against the known security issues
on all platforms but of course it cannot guard you against the already loaded potentially harmful types.
Please also note that SafeMode cannot prevent deserializing invalid content if a serializable type does not implement ISerializable
and it does not validate the incoming SerializationInfo in its serialization constructor. All serializable types that can have an invalid state regarding the field values
should implement ISerializable and should throw a SerializationException from their serialization constructor if validation fails.
Other exceptions thrown by the constructor will be wrapped into a SerializationException.
To be completely secured use binary serialization in-process only, or (especially when targeting the .NET Framework), set the Binder property to a SerializationBinder
instance that uses strict mapping. For example, you can use the CustomSerializationBinder class with handlers that throw exceptions for unexpected assemblies and types.
Please also note that if the Binder property is set, then using SafeMode cannot prevent loading assemblies by the binder itself.
It can just assure that if the binder returns , then the default resolve logic will not allow loading assemblies. The binders in this library that can perform automatic
type resolving, such the WeakAssemblySerializationBinder and ForwardedTypesSerializationBinder have their own SafeMode property.
If you use them, make sure to set their SafeMode property to to prevent loading assemblies by the binders themselves.
Similarly, if the SurrogateSelector property is set, then they provide a custom serialization even for types that are not serializable. The surrogate selectors in this library,
such as the CustomSerializerSurrogateSelector and NameInvariantSurrogateSelector types have their own SafeMode property.
If you use them, make sure to set their SafeMode property to to prevent deserializing non-serializable types.
BinarySerializationFormatter aims to serialize objects effectively where the serialized data is almost always more compact than the results produced by the BinaryFormatter class.
BinarySerializationFormatter natively supports all of the primitive types and a sort of other simple types, arrays, generic and non-generic collections.
Serialization of natively supported types produce an especially compact result because these types are not serialized by traversing and storing the fields of the object graph recursively.
This means not just better performance for these types but also prevents compatibility issues between different platforms because these types are not encoded by assembly identity and type name.
Serialization of complex types can be somewhat slower for the first time than by
BinaryFormatter but the serialized result is almost always shorter than the one by
BinaryFormatter,
especially when generic types are involved.
Even if a type is not marked to be serializable by the SerializableAttribute, then you can use the RecursiveSerializationAsFallback option to force their serialization.
Alternatively, you can implement the IBinarySerializable interface, which can be used to produce a more compact custom serialization than the one provided by implementing the ISerializable interface.
A custom serialization logic can be applied also by setting the SurrogateSelector property.
Similarly to
BinaryFormatter,
ISerializable implementations are also supported, and they are considered only for types marked by the
SerializableAttribute, unless
the
RecursiveSerializationAsFallback option is enabled for the serialization.
As BinarySerializationFormatter implements IFormatter it fully supports SerializationBinder and ISurrogateSelector implementations.
A
SerializationBinder can be used to deserialize types of unmatching assembly identity and to specify custom type-name mappings in both directions.
Though
BinarySerializationFormatter automatically handles
TypeForwardedToAttribute and
TypeForwardedFromAttribute (see also
the
IgnoreTypeForwardedFromAttribute option), you can use also the
ForwardedTypesSerializationBinder, especially for types without a defined forwarding.
The
WeakAssemblySerializationBinder can also be general solution if you need to ignore the assembly version or the complete assembly identity on resolving a type.
If the name of the type has also been changed, then the
CustomSerializationBinder can be used.
See also the
Remarks section of the
Binder property for more details.
An
ISurrogateSelector can be used to customize serialization and deserialization. It can be used for types that cannot be handled anyway for some reason.
For example, if you need to deserialize types, whose field names have been renamed you can use the
CustomSerializerSurrogateSelector.
Or, if the produced raw data has to be compatible with the obfuscated version of a type, then it can be achieved by the
NameInvariantSurrogateSelector.
There are three ways to serialize/deserialize an object. To serialize into a byte array use the Serialize method. Its result can be deserialized by the Deserialize method.
Additionally, you can use the SerializeToStream/DeserializeFromStream methods to dump/read the result to and from a Stream, and the
the SerializeByWriter/DeserializeByReader methods to use specific BinaryWriter and BinaryReader instances for
serialization and deserialization, respectively.
In .NET Framework almost every type was serializable by
BinaryFormatter. In .NET Core this principle has been
radically changed. Many types are just simply not marked by the
SerializableAttribute anymore (eg.
MemoryStream,
CultureInfo,
Encoding), and also there are some others, which still implement
ISerializable but their
GetObjectData
throw a
PlatformNotSupportedException now. Binary serialization of these types is not recommended anymore. If you still must serialize or deserialize such types
see the
Remarks section of the
CustomSerializerSurrogateSelector for more details.
Following types are natively supported. When these types are serialized, no recursive traversal of the fields occurs:
- Serializing Enum types will result a longer raw data than serializing their numeric value, though the result will be still shorter than the one produced by BinaryFormatter.
- If KeyValuePairTKey, TValue contains non-natively supported type arguments or DictionaryEntry has non-natively supported keys an values, then for them recursive serialization may occur.
If they contain non-serializable types, then the RecursiveSerializationAsFallback option should be enabled.
Following generic collections are natively supported. When their generic arguments are one of the simple types or other supported collections, then no recursive traversal of the fields occurs:
- Arrays can be single- and multidimensional, jagged (array of arrays) and don't have to be zero index-based. Arrays and other generic collections can be nested.
- If a collection uses a non-default IEqualityComparerT or IComparerT implementation, then it is possible that the type cannot be serialized without enabling
RecursiveSerializationAsFallback option, unless the comparer is decorated by SerializableAttribute or implements the IBinarySerializable interface.
- If an Array has Object element type or Object is used in generic arguments of the collections above and an element is not a natively supported type, then recursive serialization of fields
may occur. For non-serializable types the RecursiveSerializationAsFallback option might be enabled.
- Even if a generic collection of Object contains natively supported types only, the result will be somewhat longer than in case of a more specific element type.
The shortest result can be achieved by using classes or value types as array base types and generic parameters.
Following non-generic collections are natively supported. When they contain only other natively supported elements, then no recursive traversal of the fields occurs:
BinarySerializationFormatter supports calling methods decorated by OnSerializingAttribute, OnSerializedAttribute,
OnDeserializingAttribute and OnDeserializedAttribute as well as calling IDeserializationCallback.OnDeserialization method.
Attributes should be used on methods that have a single StreamingContext parameter.
Please note that if a value type was serialized by the
CompactSerializationOfStructures option, then the method of
OnDeserializingAttribute can be invoked
only after restoring the whole content so fields will be already restored.
The following example demonstrates the length difference produced by the
BinarySerializationFormatter and
BinaryFormatter classes. Feel free to change the generated type.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using KGySoft.CoreLibraries;
using KGySoft.Serialization.Binary;
public static class Example
{
public static void Main()
{
IFormatter formatter;
// feel free to change the type in NextObject<>
var instance = ThreadSafeRandom.Instance.NextObject<Dictionary<int, List<string>>>();
Console.WriteLine("Generated object: " + Dump(instance));
using (var ms = new MemoryStream())
{
// serializing by KGy SOFT version:
formatter = new BinarySerializationFormatter();
formatter.Serialize(ms, instance);
// deserialization:
ms.Position = 0L;
object deserialized = formatter.Deserialize(ms);
Console.WriteLine("Deserialized object " + Dump(deserialized));
Console.WriteLine("Length by BinarySerializationFormatter: " + ms.Length);
}
using (var ms = new MemoryStream())
{
// serializing by System version:
formatter = new BinaryFormatter();
formatter.Serialize(ms, instance);
Console.WriteLine("Length by BinaryFormatter: " + ms.Length);
}
}
private static string Dump(object o)
{
if (o == null)
return "<null>";
if (o is IConvertible convertible)
return convertible.ToString(CultureInfo.InvariantCulture);
if (o is IEnumerable enumerable)
return $"[{enumerable.Cast<object>().Select(Dump).Join(", ")}]";
return $"{{{o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => $"{p.Name} = {Dump(p.GetValue(o))}").Join(", ")}}}";
}
}
// This code example produces a similar output to this one:
// Generated object: [{Key = 1418272504, Value = [aqez]}, {Key = 552276491, Value = [addejibude, yifefa]}]
// Deserialized object [{Key = 1418272504, Value = [aqez]}, {Key = 552276491, Value = [addejibude, yifefa]}]
// Length by BinarySerializationFormatter: 50
// Length by BinaryFormatter: 2217