1、场景
创建一个学生信息管理系统,具体要求如下:
1.1 数据需求
学生信息包括:学号、姓名、年龄、性别、专业、班级。
1.2 基本功能需求(每组可以自行完善)
- 学生信息添加(学生信息从键盘上输入,保存到磁盘文件)
- 学生信息删除(按学号删除)
- 学生信息查询(提供两种查询方式:按学号查询、按姓名查询,要求使用方法的重载实现)
2、系统设计
2.1 在新建控制台应用程序,项目名为StudentManagement。
2.2 添加一个文件读写类FileAccessOperate,至少包括2个方法,文件的读方法和文件写方法。读方法设计时,需要用到集合类,将读取到的所有学生添加到该集合,例如arraylist;写方法设计时,注意每次向文件写入一行,即每个学生占去一行。
using System;
using System.Linq;
using System.Text;
//using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace StudentManagement
{
/*添加一个文件读写类FileAccess,至少包括2个方法,文件的读方法和文件写方法。
* 读方法设计时,需要用到集合类,将读取到的所有学生添加到该集合,
* 例如arraylist;写方法设计时,注意每次向文件写入一行,即每个学生占去一行。*/
class FileAccessOperate
{
static string txtDictionary=@"e:\01111104\";
//写方法
public void StuWrite(List<Student> stuList)
{
string path = txtDictionary + "stu.dat"; //学生信息存储路径
FileInfo fi = new FileInfo(path);
//判断文件是否存在
if (fi.Exists == false)
{
FileStream fs = new FileStream(path,FileMode.Create);
fs.Close();
fi = new FileInfo(path);
}
//判断文件是否为空,即是否是第一次序列化存储
if (fi.Length > 0)
{
//如果不为空,即已经进行过序列化存储,需将之前存的信息,反序列化读取,添加到要存储的对象集,覆盖存储
List<Student> StuListRead = StuRead();
foreach (Student stu in StuListRead)
{
stuList.Add(stu);
}
}
Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter(); //创建序列化对象
//序列化
bf.Serialize(stream, stuList);
stream.Close();
}
//删除学生
public void DeleteStu(int num)
{
List<Student> stuList = StuRead();
for (int i = 0; i < stuList.Count; i++)
{
if (stuList[i].StuNum == num)
stuList.Remove(stuList[i]);
}
string path = txtDictionary + "stu.dat"; //学生信息存储路径
Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter(); //创建序列化对象
bf.Serialize(stream, stuList);
stream.Close();
}
//读方法
public List<Student> StuRead()
{
string path=txtDictionary+"stu.dat"; //学生信息存储路径
FileStream stream = new FileStream(path,FileMode.Open,FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter(); //创建序列化对象
List<Student> stuList;
stuList = bf.Deserialize(stream) as List<Student>;
stream.Close();
return stuList;
}
}
}
2.3 添加一个学生类