Question

I am using the BinaryFormatter and a MemoryStream to serialize an object and then store it in a database as a binary blob. I then retrieve the data from the database and deserialize using binaryformatter and memory stream.

However, when I attempt to deserialize the object I often get exceptions being thrown. Most notably 'an object with the same key already exists' or 'cannot convert string to int64'

Does anyone have an idea as to why the deserialize craps out? or how to find out what dictionary object is having troubles?

My serialize functions follow...

private byte[] SerializeUserData(UserData ud)
{
    byte[] data = null;
    using (MemoryStream ms = new MemoryStream())
    {
        ms.Seek(0, SeekOrigin.Begin);
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, ud);
        data = ms.ToArray();
    }
    return data;
}

private UserData Deserialize()
{
    UserData ud = null;
    using (MemoryStream ms = new MemoryStream(mSession.BinarySession))
    {
        BinaryFormatter bf = new BinaryFormatter();
        ud = bf.Deserialize(ms) as UserData;
    }
    return ud; 
}

The UserData class is a bit of a monster, but it is marked as [serializable] and all classes in its object tree are also marked as [serializable]. Part of this class follows:

[Serializable]
public class UserData
{
        public UserData() { Clear(); }
        public Guid Id { get; set; }

        public Account Account { get; set; }
        public List<Account> OldAccounts{ get; set; }

        public void Clear()
        {
          Account = null;
          OldAccounts = new List<Account>();
          Id = Guid.NewGuid();
        }
}
Was it helpful?

Solution

I haven't tried this in recent versions of the framework, but I think the rule of thumb is probably still good, don't use the BinaryFormatter with automatic properties.

The problem is, the BinaryFormatter uses the backing fields and not the properties for doing serialization/ deserialization. In the case of auto properties, the backing field is generated at compile time. And it is not guaranteed to be the same each time. This could mean that you deserialize your object and you don't get back exactly what you put in.

For more read this: Automatic Properties and the BinaryFormatter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top