Serializing a class into a byte array?

O

Ole

Hi,

Was ealier advised (in c# group) to use the binary serializer to
serialize/deserialize a class into/from a byte array but to my confusion the
method isn't present in the CF2 for which I'm writing my code.

Any good idea to serialize/deserialize an instant of a class into/from a
byte array in C# for CF 2.0?

Thanks
Ole
 
M

Marc Gravell

I haven't done much CF, but I have been working on a "protocol buffers"
implementation, which works on all .NET variants (including CF2):

http://code.google.com/p/protobuf-net/

That said, the local CF experts in this group probably know many more
tools to do the same ;-p

Marc
 
S

Simon Hart [MVP]

I've always written my serialization using the XmlSerializer class. As you
found out the binary serializer is not supported on the CF so you'd have to
write your own.

There are some examples out in the field not sure how good as I've never
looked into it in great detail. Do you want binary serialization purely for
network bandwidth reasons? if so if you don't want the hassle of writing your
own serializer you could serialize using XML then compress using Compression
available in CF 3.5. I know it''s not the same but closer than raw XML.
 
O

Ole

Thanks - bandwidth is not a problem so XML will work - do you have an
example on how to do it so that the serialized XML can be transferred into a
byte array (and not a sream)?

Thanks
Ole
 
M

Marc Gravell

You should be able to use MemoryStream on CF. Use your favorite
serializer (such as XmlSerializer) to write to the MemoryStream, then
call .ToArray() on the MemoryStream.

Marc
 
S

Simon Hart [MVP]

I am actually in the middle of writing a blog post that shows how to add a
proxy server address to a network in Networking settings under WM. Part of
this shows how to serialize XML. I will be publishing this over the next
couple of days.

Sending a byte array is fairly trivial. Converting a serialized peice of XML
to a byte array could be done as follows:
byte[] bytes = Encoding.Unicode.GetBytes(myXML());

Serializing is also fairly easy something like the following should work:

public string Serialize()
{
StringWriter sw = null;
StringBuilder sb = null;
try
{
sb = new StringBuilder();
sw = new StringWriter(sb);
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(sw, this, ns);
}
catch (XmlException ex)
{
throw ex;
}
catch (ArgumentNullException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (sw != null)
sw.Close();
}
return sb.ToString();
}

--
Simon Hart
Visual Developer - Device Application Development MVP
http://www.simonrhart.com
 

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