Search code examples
c#serializationbinarydeserializationbinaryfiles

How to Binary Serializer Custom Class


I've this custom class:

public class MyClass
{ 
    private byte byteValue;
    private int intValue;
    private MyClass myClass1= null;
    private MyClass myClass2 = null;
}

obviously I also have constructor and get/set methods.

In my main form I initialize a lot of MyClass object (note that in MyClass object I have reference to other 2 MyClass objects). After initialization I iterate through a first MyClass item, call it for instance "root". So, for example I do something like:

MyClass myClassTest = root.getMyClass1();
MyClass myClassTest2 = myClassTest.getMyClass1();

and so on.

No I want to store in a binary file, all the MyClass object instantiated, in order to get them again after software restart.

I have totally no idea on how to do this, can someone please help me? Thanks.


Solution

  • First add the attribute [Serializable] before the class declaration. More about the attributes go to: https://msdn.microsoft.com/en-us/library/z0w1kczw.aspx

    [Serializable]
    public class MyClass
    { 
        private byte byteValue;
        private int intValue;
        private MyClass myClass1= null;
        private MyClass myClass2 = null;
    }
    

    Note: all the class members must be also serializable. For serializing the object to binary you can use the following code sample:

    using (Stream stream = File.Open(serializationPath, FileMode.Create))
            {
                var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                binaryFormatter.Serialize(stream, objectToSerialize);
                stream.Close();
            }
    

    And for the deserializing from binary:

    using (Stream stream = File.Open(serializationFile, FileMode.Open))
            {
                var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    
                deserializedObject = (MyClass)binaryFormatter.Deserialize(stream);
            }