XML : Need to show try/catch error in text and continue with XML serialization

This app should catch the error if the file doesn't exist and write the error to richtextbox that I have, but it's not doing it, it just creates a new student.xml file. When I wrote the code, it was showing the error and creating new file. What I am doing wrong, I can't figure out? It should be XML serialization.

      string filename = "student.xml";      List<Student> s = new List<Student>();      private void Form1_Load(object sender, EventArgs e)      {         try {              XmlSerializer x = new XmlSerializer(typeof(List<Student>));              TextReader tr = new StreamReader(filename);              s = (List<Student>)x.Deserialize(tr);               textBox1.Text = Convert.ToString(s[s.Count-1].name);              textBox2.Text = Convert.ToString(s[s.Count - 1].lastName);              tr.Close();           }           catch(Exception xml)            {               richTextBox1.AppendText(xml.Message);            }      }        private void button1_Click(object sender, EventArgs e)      {          try          {              Student b = new Student();               b.name = textBox1.Text;              b.lastName = textBox2.Text;              s.Add(b);              XmlSerializer x = new XmlSerializer(typeof(List<Student>));              TextWriter writer = new StreamWriter(filename);              x.Serialize(writer, s);              writer.Close();              richTextBox1.Clear();          }           catch (Exception ex)          {              richTextBox1.AppendText(ex.Message);          }    

I tried to throw in If clause that should check it first then write name and surname to XML file, but in this case it only showed the error, it didn't create the file.

          try          {              if (!File.Exist("student.xml"))                  throw new FileNotFoundException();              // The rest of code          }          catch (FileNotFoundException)          {              MessageBox.Show("File is not found.");          }          catch (Exception ex)          {              MessageBox.Show(ex.Message);          }    

No comments:

Post a Comment