Binary Serialization to and from Memory Variables in C#
Binary serialization come sometimes come in handy, when an alternative to XML Serialization is needed.
Serialize to Byte Array:
publicstaticbyte[] BinarySerialize(object Source)
{
var formatter = new BinaryFormatter();
byte[] bytes;
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, Source);
stream.Seek(0, 0);
bytes = stream.ToArray();
}
return bytes;
}
Deserialize from Byte Array to specified type:
publicstatic T BinaryDeserialize<T>(byte[] Source)
{
var formatter = new BinaryFormatter();
T value;
using (var stream = new MemoryStream(Source, 0, Source.Length))
{
value = (T) formatter.Deserialize(stream);
}
returnvalue;
}
Written By: mycodeshare on March 26, 2009 at 22:57
Submit a comment, suggestion, or additional information about this snippet
If you login or register,
you'll be able to post a comment or provide feedback about this snippet.