回复 5楼 qubo1982
											你没有连接到txt文档啊??										
					
	 2011-03-31 16:46
	    2011-03-31 16:46
   程序代码:
程序代码:    public class Student//新建一个学生类,包含学生的信息
    {
        public string Name { get; set; }//姓名
        public string No { get; set; }//学号
        public string Sex { get; set; }
        public int Age { get; set; }
        public Student(string name, string no , string sex, int age)
        {
            this.Name = name;
            this.Age = age;
            this.Sex = sex;
            this.No = no;
        }
        public override string ToString()
        {
            return "姓名:" + Name + ", 年龄:" + Age + ",性别:" + Sex + ",学号:" + No;
        }
    }2、定义一个学生管理类StudentManager,负责对学生的增、删、改、查: 程序代码:
程序代码:public class StudentManager
{
    private static List<Student> StudentList = null;
    public static void ReadFromFile()    // 从文件中读取数据
    {
        StudentList = new List<Student>();
        // 读取并解析学生信息,添加到StudentList中
        ...
    }
    public static void Save()
    {
        // 将StudentList保存到文件中
        ...
    }
    public static List<Student> GetAllStudents()
    {
        if (StudentList == null) ReadFromFile();
        return StudentList.ToList();    // 返回StudentList的副本
    }
    public static Student SearchByName(string name)
    {
        var stu = StudentList.FirstOrDefault(a => a.Name == name);
        return stu;
    }
    public static Student SearchByNo(string no)
    {
        var stu = StudentList.FirstOrDefault(a => a.No == no);
        return stu;
    }
    public static Student DeleteByName(string name)
    {
        var stu = SearchByName(name);
        if (stu != null) StudentList.Remove(stu);
        return stu;
    }
    public static Student DeleteByNo(string no)
    {
        var stu = SearchByNo(no);
        if (stu != null) StudentList.Remove(stu);
        return stu;
    }
    public static void Add(Student stu)
    {
        StudentList.Add(stu);
    }
}  程序代码:
程序代码:StudentManager.ReadFromFile();
StudentManager.Add(new Student(....));
var stu = StudentManager.SearchByName("张三");
if (stu == null) ....
else Console.WriteLine(stu);
stu.Age = 20;
....
StudentManager.Save();

 2011-03-31 19:16
	    2011-03-31 19:16
   2011-03-31 19:25
	    2011-03-31 19:25
   2011-03-31 19:30
	    2011-03-31 19:30
   2011-03-31 22:16
	    2011-03-31 22:16
   程序代码:
程序代码:if (!File.Exists("信息.txt")) return;
StreamReader sr = File.OpenText("信息.txt");
while((string info = sr.ReadLine()) != null)
{
    // 解析info字符串,生成Student对象,然后添加到StudentList中
    // 比如,Student对象的数据时以","分割的:
    string[] ss = info.Split(',');
    Student stu = new Student
    {
        Name = ss[0],
        No = ss[1],
        Sex = ss[2],
        Age = int.Parse(ss[2])
    }
    StudentList.Add(stu);
}
sr.Close();
保存信息: 程序代码:
程序代码:var sw = new StreamWriter("信息.txt");
foreach (var stu in StudentList)
{
    sw.WriteLine(stu.Name + "," + stu.No + "," + stu.Sex + "," + stu.Age);
}
sw.Close();

 2011-04-01 20:51
	    2011-04-01 20:51