2013-06-18 28 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本身。

相關問題