1

Here is my code for Deserializer for byte[] object

public static T DeserializeObject<T>(byte[] xml)
{
    //BinaryFormatter xs = new BinaryFormatter();
    MemoryStream memoryStream=new MemoryStream(xml);
    XmlSerializer xs = new XmlSerializer(typeof(T));
    return (T)xs.Deserialize(memoryStream);
} 

It gives error There is an error in XML document

InnerException Invalid character in the given encoding

How can I Deserialize it?

Calling funcation:

    void svc_Get_Conn(object send, GetConnCompletedEventArgs e)
    {  
        CookieContainer con =DeserializeObject<CookieContainer>(e.Result);
    }

Following funcation is from Service1.svc.cs

public static byte[] SerializeObject<T>(T obj) 
    { 
        try 
        {
            using (MemoryStream memoryStream = new MemoryStream()) 
            { 
                BinaryFormatter xs = new BinaryFormatter(); 
                xs.Serialize(memoryStream, obj); 
                return memoryStream.ToArray(); 
            } 
        } 
        catch 
        { 
            return null; 
        } 
    }
Ajay
  • 6,418
  • 18
  • 79
  • 130

1 Answers1

3

XmlSerializer can't be used to deserialize something created with BinaryFormatter1.

Solutions:

  1. Use XmlSerializer to serialize the data, or;
  2. Use BinaryFormatter to deserialize the data, or;
  3. Use an alternative for serialization and deserialization.

Alternatives include Json.NET and protobuf-net, which both offer .NET Compact Framework (Windows Phone) builds. There is also DataContractSerializer, which is standard in "normal" .NET, but I am not sure what support it has on CF.


1 Serialization formats are generally not interchangeable and trying to use the non-compatible pair in this case makes as much sense as serializing as JSON and trying to deserialize as ANS.1 (something distinctly not JSON).

XmlSerializer:

Serializes and deserializes objects into and from XML documents.

BinaryFormatter:

Serializes and deserializes [objects into and from] [an internal] binary format.