开发者

convert object(i.e any object like person, employee) to byte[] in silverlight

i have a person object and need to store it as byte[] and again retrieve that byte[] and convert to person object a开发者_StackOverflownd BinaryFormatter is not availabe in silverlight


Because the namespaces mentioned by t0mm13b are not part of the Silverlight .NET engine, the correct way to is to use this workaround leveraging the data contract serializer:

http://forums.silverlight.net/forums/t/23161.aspx

From the link:

string SerializeWithDCS(object obj)
{
    if (obj == null) throw new ArgumentNullException("obj");
    DataContractSerializer dcs = new DataContractSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    dcs.WriteObject(ms, obj);
    return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position);
}


If you really need binary and want it to be super fast and very small, then you should use protobuf from Google.

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

Look at these performance numbers. Protobuf is far and away the fastest and smallest.

convert object(i.e any object like person, employee) to byte[] in silverlight

I've used it for WCF <--> Silverlight with success and would not hesitate to use it again for a new project.


I have used XML Serializer to convert the object to a string and them convert the string to byte[] successfully in Silverlight.

object address = new Address();

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Address));
            StringBuilder stringBuilder = new StringBuilder();
            using (StringWriter writer = new StringWriter(stringBuilder))
            {
                serializer.Serialize(writer, address);
            }

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(stringBuilder.ToString());


Look at custom binary serialization and compression here

and here


Use the serialized class to convert the object into a byte via using a MemoryStream

using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

....
byte[] bPersonInfo = null;
using (MemoryStream mStream = new MemoryStream())
{
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
     bf.Serialize(mStream, personInfo);
     bPersonInfo = mStream.ToArray();
}
....
// Do what you have to do with bPersonInfo which is a byte Array...

// To Convert it back
PersonInfo pInfo = null;
using (MemoryStream mStream = new MemoryStream(bPersonInfo)){
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter();
     pInfo = (PersonInfo)bf.DeSerialize(mStream);
}
// Now pInfo is a PersonInfo object.

Hope this helps, Best regards, Tom.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜