I use BinaryFormatter and MemoryStream to serialize an object and then save it in the database as a binary blob. Then I retrieve the data from the database and deserialize it using binary formatting and a memory stream.
However, when I try to deserialize an object, I often get exceptions. Most notably, 'an object with the same key already exists' or 'cannot convert string to int64'
Does anyone have an idea on why bones are deserialized? or how to find out what problems with the dictionary problems arise?
My serialization 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(); } }
source share