Hi,
"Evan Camilleri" <evan@holisticr d.com.nospamwro te in message
news:eeVmw9%236 HHA.5424@TK2MSF TNGP02.phx.gbl. ..
>
How can I trasform (as fast as possible) an object to a binary memory
stream?
You can use Serialization, in case that the object is serializable. In any
case it will consist in a number of calls to BitConverter.Ge tBytes() method.
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);
}
}
Comment