How can I use BinaryFormatter in Windows Phone 7.
I use this using System.Runtime.Serialization.Formatters.Binary
in service1.svc.cs but I can't use this Reference in windows phone 7.
Is there any solution to this?
My Code For DeserializeObject
public static T DeserializeObject<T>(byte[] xml)
{
BinaryFormatter xs = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream(xml);
return (T)xs.Deserialize(memoryStream);
}
BinaryFormatter gives error in windows phone 7. So how can I Deserialize. What changes that I have to do in this code?
As @driis mentioned, you cannot use BinaryFormatter
on Windows Phone. You can use the binary encoding in a WCF endpoint (i.e., an endpoint whose binding is a custom binding with the BinaryMessageEncodingBindingElement
and the HttpTransportBindingElement
), and that will be supported on WP7. You just cannot use the binary formatter there.
Update following comment:
Looking at your code, it's not only that code that needs to be changed - you need to change the service code as well, to serialize an object in a format which is supported in Silverlight. You can use the DataContractSerializer
, with a binary reader / writer, or you can use another library which is supported in both cases. For example, the code below should work in both desktop and SL versions:
public static T DeserializeObject<T>(byte[] xml)
{
using (MemoryStream memoryStream = new MemoryStream(xml))
{
using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(
memoryStream, XmlDictionaryReaderQuotas.Max))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
return (T)dcs.ReadObject(reader);
}
}
}
And on the server:
public static byte[] SerializeObject<T>(T obj)
{
using (MemoryStream ms = new MemoryStream())
{
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
dcs.WriteObject(writer, obj);
writer.Flush();
return ms.ToArray();
}
}
}
BinaryFormatter is not supported in Windows Phone 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With