Evan Camilleri wrote:
How can I trasform (as fast as possible) an object to a binary memory
stream?
Simple code:
public static byte[] Object2ByteArray(object o)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, o);
return ms.ToArray();
}
public static object ByteArray2Object(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[] Object2ByteArray(T o)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, o);
return ms.ToArray();
}
public static T ByteArray2Object(byte[] b)
{
MemoryStream ms = new MemoryStream(b);
BinaryFormatter bf = new BinaryFormatter();
ms.Position = 0;
return (T)bf.Deserialize(ms);
}
}
Arne