Object to Byte[]

aewarnick

Well-known member
Joined
Jan 29, 2003
Messages
1,031
I found lots and lots of documentation on how to put an image into a Byte[] using MemoryStream but what about any object? It would be really nice if I could put any object into a Byte[].
 
I have seen on the web alot of documentation on the memory stream. It has a method ToArray() to convert an object to a byte[] but no matter what I do I cannot get memory stream to have anything in the stream. Maybe something like this:
Code:
public static byte[] GetByteArray(object o)
	{
		using (MemoryStream ms = new MemoryStream())
		{
			return ms.ToArray();
		}

	}
Although it does not work. Please help, or give me assurance that putting an object into a byte[] is impossible.
 
Last edited by a moderator:
You can, however, serialize objects into XML or binary; look into
the Xml.Serialization namespace to serialize to XML, and
the System.Runtime.Serialization.Formatters.Binary namespace to
serialize to binary.

What serialization does is take all the properties of an object and
store them in a file or in memory so you can store them easily
(to send over the internet, store settings, etc).
 
I think I figured out the exception to that. I serialize the object to disk first and then deserialize it. That works. I have no idea why I would want to do that though.
 
I did not see that you posted before I did vf. Im thinking right along your lines.

I have a question about that though. When I serialize an image to disk it never shows a thumbnail like all the other pictures do. But I can open it in any picture editor just fine. What am I doing wrong?
 
Actually im pretty sure serialization is a fast operation to perform.
I use it in my Clone method of a class i created. Worked like a charm and didnt seem to eat up alot of time. Im interested to see what the experts have to say about it.
 
What I meant was, I have no idea why I would want to serialize and then deserialize an object just to put it into a byte array. Because the only reason I want something in a byte[] is to save it to disk with a FileStream.

Serialization does seem pretty fast. I found that using method Save() to save an image to disk saves it correctly whereas serialization does not.
 
Back
Top