Create a Student class with fields RollNo, Name, City, Degree. Implement the ISerializable interface in Student class. And perform binary serialization on the Student Object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace C_SHARP
{
class Program
{
[Serializable]
class Student : ISerializable
{
public string RollNo { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Degree { get; set; }
public Student() { }
public Student(string RollNo, string Name, string City, string Degree)
{
this.RollNo = RollNo;
this.Name = Name;
this.City = City;
this.Degree = Degree;
}
protected Student(SerializationInfo info, StreamingContext context)
{
this.RollNo = info.GetString("RollNo");
this.Name = info.GetString("Name");
this.City = info.GetString("City");
this.Degree = info.GetString("Degree");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("RollNo", this.RollNo);
info.AddValue("Name", this.Name);
info.AddValue("City", this.City);
info.AddValue("Degree", this.Degree);
}
}
static void Main(string[] args)
{
Student student = new Student("448465", "Mary Clark", "London", "Math Degree");
const string FILE_NAME = "Student.dat";
Stream stream = File.OpenWrite(FILE_NAME);
//Format the object as Binary
BinaryFormatter formatter = new BinaryFormatter();
//It serialize the employee object
formatter.Serialize(stream, student);
stream.Flush();
stream.Close();
stream.Dispose();
BinaryFormatter binaryFormatter = new BinaryFormatter();
//Reading the file from the server
FileStream fs = File.Open(FILE_NAME, FileMode.Open);
Student studentRead = (Student)binaryFormatter.Deserialize(fs);
fs.Flush();
fs.Close();
fs.Dispose();
Console.WriteLine("Roll No: {0}", studentRead.RollNo);
Console.WriteLine("Name: {0}", studentRead.Name);
Console.WriteLine("City: {0}", studentRead.City);
Console.WriteLine("Degree: {0}", studentRead.Degree);
Console.ReadLine();
}
}
}
Comments
Leave a comment