Search code examples
c#.netcompact-framework

BinaryFormatter does not exist in CF. Solutions?


I need to serialize/deserialize obj in/from byte[] on compact framework but there is no BinaryFormatter, what should i do? Thanks. This is the class i am using on the server side and i want it also on the client(a device with windows mobile 6)

public class Serializer
{
    public byte[] SerializeObject(object obj)
    {
        if (obj == null)
            return null;
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, obj);
            return stream.ToArray();
        }
    }

    public object DeserializeObject(byte[] bytes)
    {
        if (bytes == null)
            return null;
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream(bytes);
        return formatter.Deserialize(stream);
    }
}

Solution

  • For your scenario, you might consider switching protobuf-net; this is not the same format as BinaryFormatter, so both client and server would need tweaks, but is a binary serialization API that works on both platforms, and is typically much smaller as an added extra. The format is actually google's "protocol buffers" encoding; very fast, platform-independent, and designed to be flexible as you add properties etc. And it is free. Some fool just gives it away.