all groups > dotnet general > august 2007 >
You're in the

dotnet general

group:

Object to Memory Stream


RE: Object to Memory Stream Peter Bromberg [C# MVP]
8/31/2007 12:24:04 PM
dotnet general:
Use the BinaryFormatter class and its Serialize method.
-- Peter
Recursion: see Recursion
site: http://www.eggheadcafe.com
unBlog: http://petesbloggerama.blogspot.com
BlogMetaFinder: http://www.blogmetafinder.com



[quoted text, click to view]
Re: Object to Memory Stream Ignacio Machin ( .NET/ C# MVP )
8/31/2007 1:48:33 PM
Hi,
[quoted text, click to view]

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.

Re: Object to Memory Stream Arne_Vajhøj
8/31/2007 6:50:28 PM
[quoted text, click to view]

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
Object to Memory Stream Evan Camilleri
8/31/2007 6:53:12 PM

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

Evan

Re: Object to Memory Stream Stanimir Stoyanov
8/31/2007 8:05:14 PM
[quoted text, click to view]

Is the object a structure or of a particular class? If a class instance, is
it your own implementation?

Best Regards,
Stanimir Stoyanov
www.stoyanoff.info | www.aeroxp.org
AddThis Social Bookmark Button