Basic Object Serialization to a STRING

G

Guest

I'm trying to figure out, from the examples, how to serialize my object to a
String variable so that I can use it to write the serialized object to a
database.

I'd like to use a BinaryFormatter and then do a Convert.ToBase64() or
something to get it into a string that'll be all text and usable in a SQL
query parameter.

But I get confused on two steps:

1. The first parameter of BinaryFormatter.Serialize() is a "stream". Can I
replace that with a string or something that can catch the data that comes
from the Object I pass?

2. How do I do the Convert.ToBase64() before it goes into the string?

So if I have a serializable object named "MyObj"...

BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(<what goes here???>, MyObj);

Thanks.

Alex
 
S

sloan

I have a complete serialization example at:
spaces.msn.com/sholliday/

search for "serialization" and you'll find it.

Are you trying to XmlSerialize?
 
G

Greg Young

1) Use a memorystream

MemoryStream m = new MemoryStream();

serialize object into stream.

2) Use MemoryStream.ToArray()
http://msdn.microsoft.com/library/d...rlrfSystemIOMemoryStreamClassToArrayTopic.asp
which will convert your memorystream into a byte []

3) Call Convert.ToBase64(yourbytes) which will return you a string that is
safe to insert into your database.

To do the opposite.

First convert your string back to bytes .. Convert.FromBase64() (returns a
byte [])

create your memorystream

MemoryStream m = new MemoryStream(yourbytes)
Deserialize your object from your stream.

Cheers,

Greg Young
MVP - C#
http://geekswithblogs.net/gyoung
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top