Evan Camilleri wrote:
How can I trasform (as fast as possible) an object to a binary memory
stream?
Simple code:
public static byte[] Object2ByteArra y(object o)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter ();
bf.Serialize(ms , o);
return ms.ToArray();
}
public static object ByteArray2Objec t(byte[] b)
{
MemoryStream ms = new MemoryStream(b) ;
BinaryFormatter bf = new BinaryFormatter ();
ms.Position = 0;
return bf.Deserialize( ms);
}
Of if you like generics:
public class Ser<T>
{
public static byte[] Object2ByteArra y(T o)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter ();
bf.Serialize(ms , o);
return ms.ToArray();
}
public static T ByteArray2Objec t(byte[] b)
{
MemoryStream ms = new MemoryStream(b) ;
BinaryFormatter bf = new BinaryFormatter ();
ms.Position = 0;
return (T)bf.Deseriali ze(ms);
}
}
Arne