An existing object (objectA) needs to be serialized into a binary file using BinaryFormatter:
FileStream fileStream = new FileStream (path, FileMode. Create );
BinaryFormatter formatter = new BinaryFormatter ();
Formatter. Serialize (fileStream, objectA );
The object objectA is defined as follows:
[Serializable ()]
Public class ObjectA
{
Public string Name
{Set; get ;}
Public event EventHandler <EventArgs> Created;
}
Note: The object ObjectA has an event: Created. If you subscribe to the ObjectA Created event in an object that cannot be serialized (such as in WinForm), an error will occur during serialization:
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Linq;
Using System. Text;
Using System. Windows. Forms;
Using System. Runtime. Serialization. Formatters. Binary;
Using System. IO;
Namespace BinarySerializer
{
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}
Private void button#click (object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog ();
If (dialog. ShowDialog () = System. Windows. Forms. DialogResult. OK)
{
Try
{
ObjectA objectA = new ObjectA {Name = ""};
If (checkBox1.Checked)
ObjectA. created + = new EventHandler <EventArgs> (objectA_Created); // when an object is serialized, if the object event is subscribed to by another object, a serialization failure error occurs, if this statement is deregistered, the serialization is successful.
String path = dialog. FileName;
FileStream fileStream = new FileStream (path, FileMode. Create );
BinaryFormatter formatter = new BinaryFormatter ();
Formatter. Serialize (fileStream, objectA );
MessageBox. Show ("saved successfully ");
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
}
}
Void objectA_Created (object sender, EventArgs e)
{
Throw new NotImplementedException ();
}
}
[Serializable ()]
Public class ObjectA
{
Public string Name
{Set; get ;}
Public event EventHandler <EventArgs> Created;