关闭XDocument实例

时间:2014-06-23 00:41:07

标签: c# xml linq-to-xml xmlreader

我一直在做这方面的研究,但仍然无法修复它。我有这个功能:

private void AddNewService()
{
    string strPath = "ServicesToExecute.xml";
    string strServicename = tbNewService.Text;
    //try
    //{
        XDocument xdDocument;
        using (XmlReader xmlReader = XmlReader.Create(strPath))
        {
            xdDocument = XDocument.Load(xmlReader); 

            XElement root = new XElement("Service");
            root.Add(new XElement("Name", strServicename));
            xdDocument.Element("ServicesToExecute").Add(root);
            xmlReader.Close();
            xdDocument.Save(strPath);      
        }

我在尝试保存文件时遇到错误......有什么想法吗?我想我错过了一些非常愚蠢的东西,但现在却看不到它。

1 个答案:

答案 0 :(得分:0)

我相信您在ServicesToExecute.xml内打开了一个名为XmlReader的文件,然后尝试将XDocument保存在同一路径中...... AKA试图覆盖该文件你有空的阅读。根据上面的@mikez,您应该使用XDocument.Load(string path)重载来简化代码:

private void AddNewService()
{
    string strPath = "ServicesToExecute.xml";
    string strServicename = tbNewService.Text;
    //try
    //{
        XDocument xdDocument = XDocument.Load(strPath);

        XElement root = new XElement("Service");
        root.Add(new XElement("Name", strServicename));
        xdDocument.Element("ServicesToExecute").Add(root);

        // Save
        xdDocument.Save(strPath);
相关问题