When a node is added to an existing XML file through a file stream, streaming data is loaded through the file object. When you write data to an XML file again after the data is processed by the Document Object, duplicate data will appear in the XML file because the data is written at the end of the stream by default. To solve this problem, we need to set the stream length to 0 to re-write the XML file.
using(FileStream fs = new FileStream(GlobalParams.XmlFileName,FileMode.Open,FileAccess.ReadWrite)) { try { XDocument doc = XDocument.Load(fs); XElement element = new XElement("Email", new XElement("EmailFrom", txtEmailAddress.Text.Trim()), new XElement("MailHost", txtSMTP.Text.Trim()), new XElement("EmailAccount", txtEmailAccount.Text.Trim()), new XElement("EmailPassword", txtEmailPassword.Text.Trim()), new XElement("SMTPPort", updSMTPPort.Value), new XElement("EnableSSL", chkSSL.Checked) ); if (!doc.Root.Descendants("EmailFrom").Any(ele => ele.Value == txtEmailAddress.Text.Trim())) { doc.Root.Element("Push_MLG").Add(element); fs.SetLength(0); doc.Save(fs); } } catch (Exception ex) { MessageBox.Show(string.Format("Failed:\t{0}", ex.Message)); return; }
Write XML data through a file stream