通过文件流写入XML数据

  通过文件流给已经存在的XML文件添加节点时,会通过文档对象加载流数据。在文档对象处理完数据之后,重新把数据写入XML文件时,因为默认是流结尾写入,那么会在XML文件中出现重复的数据。为了解决这个问题需要把流的长度设置为0,来重新写入XML文件。

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

 

posted @ 2014-09-18 16:46  眼泡肿了  阅读(649)  评论(0编辑  收藏  举报