Object to Memory Stream

  • Thread starter Thread starter Evan Camilleri
  • Start date Start date
E

Evan Camilleri

How can I trasform (as fast as possible) an object to a binary memory
stream?

Evan
 
Hi,
Evan Camilleri said:
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.GetBytes() method.
 
Evan said:
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
 
Back
Top