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();
}
}
}