How to serialize or de-serialize an object using BinaryFormatter class?
You can serialize or de-serialize an object using the Serialize or the Deserialize method of the BinaryFormatter class.
Implementation
private void Serialize(String fileName, Object obj)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream fileStream = new FileStream(fileName,FileMode.Create);
try
{
binaryFormatter.Serialize(fileStream, obj);
}
catch (SerializationException ex)
{
throw new ApplicationException("The object graph could not be serialized", ex);
}
finally
{
fileStream.Close();
}
}
The Serialize method shown above accepts a file name and the object to be serialized as parameters. It then serializes the object using a BinaryFormatter instance, and stores the serialized instance of the file.
Now, following is the DeSerialize method that accepts the name of the file where the serialized instance is stored and returns the de-serialized instance:
public Object DeSerialize(String fileName)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream fileStream = new FileStream(fileName, FileMode.Open);
try
{
fileStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(fileStream);
}
catch (SerializationException ex)
{
throw new ApplicationException("Serialization Exception: " + ex.Message);
}
finally
{
fileStream.Close();
}
return null;
}
The following code shows how you can use the Serialize and De-Serialize methods from above:
private void SerializeDemo()
{
Employee employee = new Employee();
employee.FirstName = "Micheal";
employee.LastName = "Branson";
employee.Address = "New York";
Serialize("C:\\Test\\Employee.txt", employee);
}
The above code serializes the instance of Employee class and stores the serialized instance in the Employee.txt file.
Now, to de-serialize the instance and get back the original instance, you need to call the DeSerialize method as shown below:
private void DeSerializeDemo()
{
Employee employee = (Employee)DeSerialize("C:\\Test\\Employee.txt");
Response.Write("Employee First Name: " + employee.FirstName);
Response.Write("<br>Employee Last Name: " + employee.LastName);
Response.Write("<br>Employee Address: " + employee.Address);
}
Following is output of the de-serialized employee instance:
Employee First Name: Micheal
Employee Last Name: Branson
Employee Address: New York