Exceptions when using BinaryFormatter to deserialize my serialized data

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(); } } 
+4
source share
1 answer

I have not tried this in recent versions of the framework, but I think the rule of thumb is probably still good, do not use BinaryFormatter with automatic properties.

The problem is that BinaryFormatter uses support fields, not properties for serialization / deserialization. For auto properties, a compilation field is created at compile time. And every time this is not guaranteed. This may mean that you are deserializing your object and you will not return exactly what you have enclosed.

Read More: Auto Properties and BinaryFormatter

+5
source

Source: https://habr.com/ru/post/1332539/


All Articles