using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
//引入binaryformater类的命名空间
using System.Runtime.Serialization.Formatters.Binary;
namespace TestOne
{
public partial class Form1 : Form
{
private List<student> stus = new List<student>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
stus.Add(new student("小张","男","打酱油"));
stus.Add(new student("小明", "女", "玩游戏"));
stus.Add(new student("小王", "男", "打酱油"));
//将list集合序列化
Save();
//清除list集合中所有元素
stus.Clear();
//反序列话
load();
//绑定数据源
dataGridView1.DataSource = new BindingList<student>(stus);
}
//序列号方法
public void Save()
{
//AppDomain.CurrentDomain.BaseDirectory返回一个字符串,为程序的运行时目录
FileStream stream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "one.xml", FileMode.Create);
//创建序列号对象
BinaryFormatter binary = new BinaryFormatter();
//将对象序列化到指定的文件中
binary.Serialize(stream, this.stus);
//关闭文件流
stream.Close();
}
//反序列话
public void load()
{
//创建文件流对象
FileStream stream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "one.xml", FileMode.Open);
//创建序列号对象
BinaryFormatter binary = new BinaryFormatter();
//因为Deserialize()方法,返回的是一个object对象,所以要转型
this.stus = (List<student>)binary.Deserialize(stream) ;
//关闭文件流
stream.Close();
}
}
}