Write XML data through a file stream

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.