2013-06-18 30 views
2

我有以下的,但它不是为我工作:写只是一个XML属性,而不会影响其余

static void SaveVersion(string configFile, string Version) 
    { 
      XmlDocument config = new XmlDocument(); 
      config.Load(configFile); 

      XmlNode appSettings = config.SelectSingleNode("configuration/appSettings"); 
      XmlNodeList appKids = appSettings.ChildNodes; 

      foreach (XmlNode setting in appKids) 
      { 

       if (setting.Attributes["key"].Value == "AgentVersion") 
        setting.Attributes["value"].Value = Version; 
      } 

      config.Save(configFile); 
    } 

配置文件我加载了上config.Load(configFile)如下:

<?xml version="1.0"?> 
<configuration> 
    <startup> 
    <supportedRuntime version="v2.0.50727" /> 
    </startup> 

    <appSettings> 
    <add key="AgentVersion" value="2.0.5" /> 
    <add key="ServerHostName" value="" /> 
    <add key="ServerIpAddress" value="127.0.0.1" /> 
    <add key="ServerPort" value="9001" /> 
    </appSettings> 
</configuration> 

我错过了什么吗?我想它会编辑那个特定的属性AgentVersion,但它并没有真正做任何事情。

回答

1

您是否知道ConfigurationManager这个类?您可以使用它来手动操作您的app.config文件,而无需执行任何操作。我不认为,除非你有一个很好的理由,你应该重新发明轮子:

static void SaveVersion(string configFile, string version) 
{ 
    var myConfig = ConfigurationManager.OpenExeConfiguration(configFile); 
    myConfig.AppSettings.Settings["AgentVersion"].Value = version; 
    myConfig.Save(); 
} 
1

试试这个:

static void SaveVersion(string configFile, string Version) 
{ 
    var config = new XmlDocument(); 
    config.Load(configFile); 

    var agentVersionElement = config.DocumentElement.SelectSingleNode("configuration/appSettings/add[@key = 'AgentVersion']") as XmlElement; 
    if (agentVersionElement != null) 
     agentVersionElement.SetAttribute("value", version); 

    config.Save(configFile); 
} 

请注意,我从DocumentElement从做SelectSingleNode,不XmlDocument本身。

相关问题