如何在C#窗体中更新和删除文本文件中的特定行

本文关键字:文件 文本 删除 窗体 更新 | 更新日期: 2023-09-27 18:26:15

我是在c#中使用文件处理程序的新手。我已经完成了插入和搜索。请帮助我如何使用以下代码进行更新和删除。

UI部分::

 private void btnAdd1_Click(object sender, EventArgs e)
 {
     StudentManager sm = new StudentManager();
     sm.AddStudent(textName.Text,textId.Text,textDpt.Text,textSem.Text);
 }
 public void btnSearch1_Click(object sender, EventArgs e)
 {
        StudentManager sm = new StudentManager();
        Student s = sm.FindStudent(textId.Text);
        if (s != null)
        {
            this.textName.Text = s.GetName();
            this.textId.Text = s.ID;
            this.textDpt.Text = s.Department; 
            this.textSem.Text = s.GetSEM();              
        }
 }

验证::

   string id = String.Empty;
   public void SetName(string name)
   {
        if(!String.IsNullOrEmpty(name))
        {
            this.name = name;
        }
    }
    public string ID
    {
        get { return id; }
        set { id = value; }
    }
   string department = String.Empty;
    public string Department
    {
        get { return department; }
        set { department = value; }
    }
    string SEM= String.Empty;
    public void SetSEM(string sem)
    {
        if (!String.IsNullOrEmpty(sem))
        {
            this.SEM = sem;
        }
    }
    public string GetSEM()
    {
        return this.SEM;
    }
     public String GetName()
    {
        return this.name;
    }
}

学生经理::

class StudentManager
{    
    ArrayList students;
    const string FILENAME = @"d:'students.txt";
    public StudentManager()
    {
        SetStudentList();
    }
    private void SetStudentList()
    {
        if (students == null)
        {
            //create a file handler
            FileHandler sfh = new FileHandler();
            //initialize the teacher list object
            students = new ArrayList();
            //Now read all the lines from the teacher.txt
            //each line represent a teacher
            string[] studentfromfile = sfh.getAllLines(@FILENAME);
            int totalstudents = studentfromfile.Length;
            //go through each teacher and create teacher object to add it to the teacher list.
            for (int i = 0; i < totalstudents; i++)
            {
                string studentinfo = studentfromfile[i];
                string[] studentinfobroken = studentinfo.Split(new char[] { ',' });
                if (studentinfobroken.Length == 4)
                {
                    //this part is being duplicated - can think how?
                    Student s = new Student();
                    s.SetName(studentinfobroken[0]);
                    s.ID= studentinfobroken[1];
                    s.Department = studentinfobroken[2];
                    s.SetSEM(studentinfobroken[3]);
                    this.students.Add(s);
                }
            }
        }
    }
 public void AddStudent(string fullname, string ID, string dept,string Semester )
 {
        Student s = new Student();
        s.SetName(fullname);
        s.ID = ID;
        s.Department = dept;
        s.SetSEM(Semester);
        this.students.Add(s);
        FileHandler sfh = new FileHandler();
        string studentInfo = Environment.NewLine + s.GetName() + "," + s.ID + "," + s.Department + "," + s.GetSEM();
        sfh.AddLine(@FILENAME, studentInfo);
    }
   public Student FindStudent(string ID)
   {
        foreach (Student s in students)
        {
            if (s.ID.Equals(ID))
            {
                return s;
            }
        }
        return null;
    }
  class FileHandler
  {
    public String[] getAllLines(string fileName)
    {
        try
        {
            String[] lines = File.ReadAllLines(@fileName);
            return lines;
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    public String GetAllText(string fileName)
    {
        try
        {
            String content = File.ReadAllText(@fileName);
            return content;
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    public void AddLine(string filename, string line)
    {
        StreamWriter sr = null;
        try
        {
            sr = new StreamWriter(@filename, true);//true for append
            sr.WriteLine(line);
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            sr.Close();
        }
    }

如何在C#窗体中更新和删除文本文件中的特定行

好的,我看过你的代码,看起来你在做了每一件小事之后都会更新你的文本文件,这是错误的方法。。(如果我错了,那么请减少你的例子中的代码,使其更容易阅读!)

您应该尝试在加载程序时,将文件中的学生加载到学生的list中。然后,当你的程序仍然存在时,你应该在任何需要的地方使用此列表。当你准备关闭程序时,然后将其写回文件。

这种方式的一个优点,除了明显的效率和易用性之外,就是可以取消更改,而不会破坏你唯一的学生副本。

例如

studentList.Remove(student) - Remove from list
studentList.Add(student) - add
studentList.Where(x => x.Name = "Joe"); - Filter

更新

studentfromfile[5] = "updated line";
File.WriteAllLines(FILENAME, studentfromfile);

删除

studentfromfile[5] = String.Empty;
studentfromfile = studentfromfile.Where(x => !String.IsNullOrEmpty(x)).ToArray();
File.WriteAllLines(FILENAME, studentfromfile);

有更好的方法可以做到这一点,比如使用Sayse建议的集合。你不应该使用ArrayLists,如果你正在创建一个以.Net 2.0及更高版本为目标的项目(使用List),它们就不是必需的,而且你不应该因为失去了堆栈竞争而抛出这样的异常。使用

try
{
   String content = File.ReadAllText(@fileName);
   return content;
}
catch (Exception e)
{
    throw; //not throw e;
}