1. 程式人生 > 實用技巧 >c#序列化反序列化

c#序列化反序列化

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

//引入名稱空間
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace TextFile
{
    public partial class FrmFile : Form
    {
        
public FrmFile() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { //封裝物件資訊 Student objStu = new Student() { Name = this.txtName.Text.Trim(), Age = Convert.ToInt16(this
.txtAge.Text.Trim()), Gender = this.txtGender.Text.Trim(), Birthday = Convert.ToDateTime(this.txtBirthday.Text.Trim()) }; //儲存到文字檔案 FileStream fs = new FileStream("C:\\objStu.obj", FileMode.Create); StreamWriter sw = new StreamWriter(fs);
//一行一行寫入文字 sw.WriteLine(objStu.Name); sw.WriteLine(objStu.Age); sw.WriteLine(objStu.Gender); sw.WriteLine(objStu.Birthday.ToShortDateString()); //關閉檔案流和寫入器 sw.Close(); fs.Close(); } private void btnRead_Click(object sender, EventArgs e) { FileStream fs = new FileStream("C:\\objStu.obj", FileMode.Open); StreamReader sr = new StreamReader(fs); //一行一行讀取 Student objStu = new Student() { Name = sr.ReadLine(), Age = Convert.ToInt16(sr.ReadLine()), Gender = sr.ReadLine(), Birthday = Convert.ToDateTime(sr.ReadLine()) }; sr.Close(); fs.Close(); this.txtName.Text = objStu.Name; this.txtAge.Text = objStu.Age.ToString(); this.txtGender.Text = objStu.Gender; this.txtBirthday.Text = objStu.Birthday.ToShortDateString(); } private void btnSerialize_Click(object sender, EventArgs e) { //封裝物件資訊 Student objStu = new Student() { Name = this.txtName.Text.Trim(), Age = Convert.ToInt16(this.txtAge.Text.Trim()), Gender = this.txtGender.Text.Trim(), Birthday = Convert.ToDateTime(this.txtBirthday.Text.Trim()) }; //【1】建立檔案流 FileStream fs = new FileStream("C:\\objStu.obj", FileMode.Create); //【2】建立二進位制格式化器 BinaryFormatter formatter = new BinaryFormatter(); //【3】呼叫序列化方法 formatter.Serialize(fs, objStu); //【4】關閉檔案流 fs.Close(); } private void btnDeserialize_Click(object sender, EventArgs e) { //【1】建立檔案流 FileStream fs = new FileStream("C:\\objStu.obj", FileMode.Open); //【2】建立二進位制格式化器 BinaryFormatter formatter = new BinaryFormatter(); //【3】呼叫序列化方法 Student objStu = (Student)formatter.Deserialize(fs); //【4】關閉檔案流 fs.Close(); //顯示物件屬性 this.txtName.Text = objStu.Name; this.txtAge.Text = objStu.Age.ToString(); this.txtGender.Text = objStu.Gender; this.txtBirthday.Text = objStu.Birthday.ToShortDateString(); } } }