- //序列化
- private void button3_Click(object sender, EventArgs e)
- {
- try
- {
- //我这里是只用了一个文本,大家可以使用其他的对象。
- string a = textBox1.Text.ToString().Trim();
- //创建一个序列化的文件
- FileStream fs = new FileStream("student.dat", FileMode.Create);
- //这个是转换机
- BinaryFormatter bin = new BinaryFormatter();
- //下面的是转换函数,将对象进行序列化
- bin.Serialize(fs, a);
- //把文件流关死!
- fs.Close();
- MessageBox.Show("序列化成功!");
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- //反序列化
- private void button4_Click(object sender, EventArgs e)
- {
- try
- {
- //打开序列化的文件
- FileStream fs = new FileStream("student.dat", FileMode.OpenOrCreate);
- //创建转换机。
- BinaryFormatter bin = new BinaryFormatter();
- //将对象进行反序列化
- textBox2.Text = bin.Deserialize(fs).ToString();
- fs.Close();
- MessageBox.Show("反序列化成功!");
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/3007201513274.html
来源: http://www.codesnippet.cn/detail/3007201513274.html