-4

I am new in using file handler in c#. I have done insert and search. Please help me how can I do update and delete using this following code.

UI part::

 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();              
        }
 }

validation::

   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;
    }

}

studentManager::

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();
        }
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • What's the line you want to update and delete? How do you find it? – keyboardP Aug 02 '13 at 21:10
  • 2
    To be honest with you, I've just scrolled straight to the comment section right after reading your opening line. You should *only* include the relevant pieces of code, it puts people off – Sayse Aug 02 '13 at 21:14
  • first i have inserted some lines in my student.txt file..then i search a specfic student info through id..then i want to delete that student info..and update!!please sir help me.. – Riasat Raihan Riasat Aug 02 '13 at 21:14
  • 1
    do not post all of your code.. this is not a code review session post the code that's only relevant to your question. also there are tons of examples on Google as well as Stackoverflow were if you were to have done a simple search you probably would have had your solution by now – MethodMan Aug 02 '13 at 21:14
  • How is the text file formatted? Where does the ID appear in the line? You've given enough code (too much! :)) but not enough information on the relevant details. – keyboardP Aug 02 '13 at 21:15
  • there are many ways to update and delete..but i m new at this..so i added this code so that u can help me following this code.. – Riasat Raihan Riasat Aug 02 '13 at 21:16
  • We can only help if you if we know what's going on. No one is going to look through all your code so cut that down to the relevant bits. You also haven't answered my question about how the text file is formatted. No one can confidently answer your question with the current information. – keyboardP Aug 02 '13 at 21:18
  • i m storing input data in a text file..and i can search that line that i ve taken input..code has those(insert and search part)..I want to knw how to update and delete.. – Riasat Raihan Riasat Aug 02 '13 at 21:25

2 Answers2

2

Ok I've looked over your code and it looks as though you update your textfile after every little thing you do which is the wrong approach.. (If I'm wrong then please reduce the code in your example to make it easier to read!)

What you should be trying to do is when your program loads, load the students from the file into a list of Students. Then whilst your program persists you should use this list wherever you need it. When you are ready to close your program, then you write it back to the file.

One advantage of this way, other than the obvious efficiency and ease of use, is that changes can be cancelled without your only copy of students being destroyed.

e.g

studentList.Remove(student) - Remove from list
studentList.Add(student) - add
studentList.Where(x => x.Name = "Joe"); - Filter
Sayse
  • 42,633
  • 14
  • 77
  • 146
1

Update

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

Delete

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

There are better ways of doing this such as using a collection as Sayse recommends. You shouldn't use ArrayLists, they're not required if you're creating a project that targets .Net 2.0 and above (use List), and you shouldn't throw exceptions like that because you're losing the stacktrace. Use

try
{
   String content = File.ReadAllText(@fileName);
   return content;
}
catch (Exception e)
{
    throw; //not throw e;
}
keyboardP
  • 68,824
  • 13
  • 156
  • 205