private void AddUserToListBox() { User user = new User(tbUserName.Text, tbUserEmail.Text); Users.Add(user); EmailsList.Add(user.Email); SaveUserToXML(user); tbUserEmail.Text = String.Empty; tbUserName.Text = String.Empty; }
private void SaveUserToXML(User inputUser) { try { if (File.Exists("users.xml") == false) { XDocument xmlDocument = new XDocument(); XElement users = new XElement("Users"); XElement user = new XElement("User"); user.Add(new XElement("FullName", inputUser.FullName), new XElement("Email", inputUser.Email)); users.Add(user); xmlDocument.Add(users); xmlDocument.Save("users.xml"); } else { XDocument xDocument = XDocument.Load("users.xml"); XElement root = xDocument.Element("Users"); XElement particularUser = xDocument.Descendants("Users"). Descendants("User"). Where(u => u.Element("FullName").Value == inputUser.FullName).FirstOrDefault(); if (particularUser != null) { MessageBox.Show("There is already such user in the list"); return; } IEnumerable<XElement> rows = root.Descendants("User"); XElement firstRow = rows.First(); firstRow.AddBeforeSelf( new XElement("User", new XElement("FullName", inputUser.FullName), new XElement("Email", inputUser.Email))); xDocument.Save("users.xml"); } } catch (Exception e) { MessageBox.Show(e.Message); } }