繁体   English   中英

如何在C#中执行序列化和反序列化?

[英]How to perform serialization and deserialization in C#?

我正在尝试编写用于序列化和反序列化的程序。 但是我的程序抛出异常

尝试反序列化空流。 在“ mp =(employee)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();
    }
}
}

FileMode.Create将删除该文件(如果已存在)。 您要Open

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM