因為要對文件做操作,所以首先還是要引入命名空間
1 //引入命名空間 2 using System.IO;
一、保存對象數據到文本文件中。
注意對象明確原則;
1 //封裝數據; 2 Student objStudent = new Student() //對象初始化器 3 { 4 StudentName = this.txtStudentName.Text.Trim(), 5 Age = Convert.ToInt32(this.txtAge.Text.Trim()), 6 Birthday = Convert.ToDateTime(this.txtBirthday.Text.Trim()), 7 Gender = this.txtGender.Text.Trim() 8 }; 9 10 //保存到文件 11 FileStream fs = new FileStream("objStudent.obj", FileMode.Create); 12 StreamWriter sw = new StreamWriter(fs); 13 //逐行寫入 14 sw.WriteLine(objStudent.StudentName); 15 sw.WriteLine(objStudent.Age); 16 sw.WriteLine(objStudent.Birthday); 17 sw.WriteLine(objStudent.Gender); 18 //關閉對象 19 sw.Close(); 20 fs.Close();
二、讀取對象數據,並顯示;
1 FileStream fs = new FileStream("objStudent.obj", FileMode.Open); 2 StreamReader sr = new StreamReader(fs); 3 //逐行讀取; 4 Student objStudent = new Student() 5 { 6 StudentName = sr.ReadLine(), 7 Age = Convert.ToInt32(sr.ReadLine()), 8 Birthday = Convert.ToDateTime(sr.ReadLine()), 9 Gender = sr.ReadLine() 10 }; 11 sr.Close(); 12 fs.Close(); 13 14 //顯示數據 15 this.txtStudentName.Text = objStudent.StudentName; 16 this.txtAge.Text = objStudent.Age.ToString(); 17 this.txtBirthday.Text = objStudent.Birthday.ToShortDateString(); 18 this.txtGender.Text = objStudent.Gender;