0

Does anybody know how I can control the deserialization process of a custom class when it has been serialized with the binary formatter?

I have my serializable class Dat which contains 2 fields:

class Dat
{
    uint A;
    [field: NonSerialized]
    object Data;
    string File;
}

What I want to do is when the class is deserialized I have no object data, and I just want to load it after its deserialized like this (in Dat class):

void AfterDeserialize()
{
    Data = File.ReadAllBytes(File);
}

Sure I could just deserialize the class and the load it afterwards but that's almost not possible because it is in a complicated tree like structure. So does anybody know how to get a event or method with is called after deserialization?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • Use a deserialization callback (look at the answers to a similar problem here: https://stackoverflow.com/questions/3500429/how-does-binaryformatter-deserialize-create-new-objects) or a `[OnDeserializing]` attribute. Also look here for a discussion about the differences between deserialization callback interface vs. attributes : https://social.msdn.microsoft.com/Forums/en-US/311b2b57-6b0a-49ed-aa96-84f69d51da0f/ideserializationcallbackondeserialization-method-called-after-the-ondeserialized-event?forum=netfxremoting Hope this helps... –  Oct 16 '18 at 15:50
  • That was it! :) Ty https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.ideserializationcallback?redirectedfrom=MSDN&view=netframework-4.7.2 Write an answer i can accept it ;) –  Oct 16 '18 at 16:53
  • Possible duplicate of [IDeserializationCallback vs OnDeserializedAttribute](https://stackoverflow.com/questions/1308373/ideserializationcallback-vs-ondeserializedattribute) –  Oct 16 '18 at 20:49
  • You should not use BinaryFormatter for new code because it is insecure. See https://aloiskraus.wordpress.com/2022/11/23/net-serialization-roundup-2022/ – Alois Kraus Dec 17 '22 at 18:13

0 Answers0