How to Binary Serializer Custom Class

佐手、 提交于 2019-12-02 02:39:37

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);
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!