日期:2014-05-18  浏览次数:21146 次

C# 泛型集合序列化和反序列化问题
各位高手,请指定一下,我这个是用Udp协议做的通信程序,现在时发送和接收泛型集合,发送没问题,接收的时候不知道怎么反序列化????报的错是“没有对象“201326592”的映射。”,原因好像是序列化后没有反回来吧!!

/发送数据  
  public void SendData()
  {
  try
  {
  //定义对方主机和端口
  IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(txtHisIP.Text), int.Parse(txtHisPort.Text));
  //实例化并赋值 
  Users user = new Users();
  user.Name = txtName.Text.Trim();
  user.Sex = txtSex.Text.Trim();
  user.Age = int.Parse(txtAge.Text.Trim());
  user.Address = txtAddress.Text.Trim();
  user.Phone = ulong.Parse(txtPhone.Text.Trim());
  user.Content = txtContent.Text.Trim();
  List<Users> list = new List<Users>();
  list.Add(user);
  //序列化集合
  FileStream fs = new FileStream("C:\\go.txt", FileMode.Open); //定义一个文件流
  BinaryFormatter bf = new BinaryFormatter(); //二进制方式
  bf.Serialize(fs, list); //序列化保存配置文件对象list
  fs.Seek(0, SeekOrigin.Begin);
  string ss = "";
  //读取出来
  using (StreamReader sr = new StreamReader(fs))
  {
  ss = sr.ReadToEnd();
  sr.Close();
  }

  #region 类序列化
  ////类序列化
  //xml = new XmlSerializer(typeof(Users));
  //ms = new MemoryStream();

  //xml.Serialize(ms, user);
  //ms.Seek(0, SeekOrigin.Begin); //将当前流的位置设为指定值
  //string str = Encoding.UTF8.GetString(ms.ToArray()); 
  #endregion
  //string to byte[]
  byte[] by = Encoding.UTF8.GetBytes(ss);
  //发送
  udpClient.Send(by, by.Length, ipPoint);

  toolsStatus.Text = "已发送!";
  fs.Close(); //关闭流
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message);
  }

接收:
//接收任何地址的数据 接收
  IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
  //接收数据,储存在byte数组里
  byte[] bytes = udpClient.Receive(ref point);
  //byte to string
  string str = Encoding.UTF8.GetString(bytes); //乱码问题
  //反序列化集合
  FileStream fs = new FileStream("F:\\go.txt", FileMode.Create);
  using (StreamWriter sw = new StreamWriter(fs))
  {
  sw.Write(str); //写入
  sw.Close();
  }
  fs.Close();

  FileStream fsf = new FileStream("F:\\go.txt", FileMode.Open);
  BinaryFormatter bf = new BinaryFormatter();
  List<Users> list = bf.Deserialize(fsf) as List<Users>; //获取

------解决方案--------------------
http://www.cnblogs.com/lindping/archive/2011/01/1