0
Я пытаюсь написать программу для сериализации и десериализации. Но моя программа бросает исключение какКак выполнить сериализацию и десериализацию в C#?
Попытка десериализации пустого потока. в строке «mp = (сотрудник) bfr.Deserialize (s);»
Я не получаю точно, что не так с моей программой.
Вот мой код
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();
}
}
}
Thank you soo much @SLaks. –