find and solve || findandsolve.com
Please wait.....

Deserialization in C#

In the C#, Deserialization in C# is the reverse process of serialization. That means we can read the object from the byte stream.

In simple words, Deserialization is the process of reconstructing an object from a previously serialized sequence of bytes.

We are going to use BinaryFormatter.Deserialize(stream) method to deserialize the stream.

 Deserialization Example in C#

using System;  

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Student
{
    public int rollNumber;
    public string fullName;
    public Student(int rollNumber, string fullName)
    {
        this.rollNumber= rollNumber;
        this.fullName= fullName;
    }
}
public class DeserializeExample
{
    public static void Main(string[] args)
    {
        FileStream stream = new FileStream("D:\\test.txt", FileMode.OpenOrCreate);
        BinaryFormatter formatter=new BinaryFormatter();
        Student objStudent=(Student)formatter.Deserialize(stream);
        Console.WriteLine("Roll Number: " + objStudent.rollNumber);
        Console.WriteLine("Full Name : " + objStudent.fullName);
        stream.Close();
    }
}  

Output

Roll Number: 2

Full Name: Sylvia