I am trying to write program for serialization and deserialization. But my program is throwing an exception as
Attempting to deserialize an empty stream. at line "mp = (employee)bfr.Deserialize(s);"
I am not getting exactly what is wrong with my program.
Here is my Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace serializationDemo
{
[Serializable()]
public class employee : ISerializable
{
public int empid;
public string empname;
public employee()
{
empid=0;
empname = null;
}
public employee(SerializationInfo info,StreamingContext ctxt)
{
empid =(int)info.GetValue("EmployeeId",typeof(int));
empname = (string)info.GetValue("EmployeeName",typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("EmployeeId",empid);
info.AddValue("EmployeeName", empname);
}
}
public class Program
{
public static void Main(string[] args)
{
employee mp = new employee();
mp.empid = 10;
mp.empname = "Waseem";
Stream s = File.Open("employee.osi", FileMode.Create);
BinaryFormatter bfr = new BinaryFormatter();
Console.WriteLine("\nWritting employee information...");
bfr.Serialize(s,mp);
s.Close();
mp = null;
s = File.Open("employee.osi", FileMode.Create);
bfr = new BinaryFormatter();
mp = (employee)bfr.Deserialize(s);
s.Close();
Console.WriteLine("Employee ID={0}", mp.empid.ToString());
Console.WriteLine("Employee Name={0}", mp.empname);
Console.ReadKey();
}
}
}
FileMode.Create
will delete the file if it already exists. You want Open
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.