Advertisement
Methods | Description |
---|---|
Serialize(Stream stream, Object object) | This method of BinaryFormatter, writes the state of the specified object to the specified stream, so that it can be saved in a file, and thus performing serialization. |
Deserialize(Stream stream) | This method of BinaryFormatter, reads the saved object from the specified stream(which is used to refer to a file in which the state of object was written to) and thus performing deserialization. |
Advertisement
//C# Example of Serialization and Deserialization
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class SerialEx
{
//An instance variable of the class
int i=0;
//Defining the Main() method of class
public static void Main(String[] ar)
{
//Creating an object of SerialEx class
SerialEx ob= new SerialEx();
//Setting the instance variable i of the object to 10
ob.i=10;
Console.WriteLine("Before Serialization the instance variable of the object has a value : " + ob.i);
try
{
//Creating an object of FileStream to write to a file
//We are going to use the FileMode OpenOrCreate to create a new file to write the saved form of object to
FileStream fs = new FileStream("E:\\File.ser", FileMode.OpenOrCreate);
//Creating an object of BinaryFormatter
BinaryFormatter bf = new BinaryFormatter();
//Serializing, i.e. saving the state of this object, ob
bf.Serialize(fs, ob);
//Closing the FileStream after writing the saved state of object to the associated file
fs.Close();
}
catch(Exception exp)
{
Console.WriteLine(exp + " while performing serialization");
}
try
{
//Creating an object of FileStream to write to a file
//We are going to use the FileMode.Open mode to open the existing file to read the saved form of object from it
FileStream fs = new FileStream("E:\\File.ser", FileMode.Open);
//Creating an object of BinaryFormatter
BinaryFormatter bf = new BinaryFormatter();
//Deserializing, i.e. restoring the object to its original state.
SerialEx ob2 = (SerialEx)bf.Deserialize(fs);
//Closing the FileStream after reading the saved state of object from its associated file
fs.Close();
Console.WriteLine("After Deserialization restored object's instance variable has a value : "+ ob2.i);
}
catch(Exception exp)
{
Console.WriteLine(exp + " while performing deserialization"));
}
}
}
Before Serialization the instance variable of the object has a value : 10
After Deserialization restored object's instance variable has a value : 10
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement