1

我有一个 WCF 服务器,它具有以下 app.config 文件:

<?xml version="1.0"?>
<configuration>   
  <system.serviceModel>   
    <services>
      <service name="MyService" behaviorConfiguration="DiscoveryBehavior">       
        <endpoint address="net.tcp://192.168.150.130:44424/ServerService/"/>        
        <endpoint name="udpDiscovery" kind="udpDiscoveryEndpoint"/>
      </service>
    </services>
  </system.serviceModel> 
</configuration>

在另一台机器上安装时,我想让它使用该机器的地址自动更新地址。我有字符串,但我不明白如何更新 app.config 文件中的“地址”项。我有以下代码,但这不起作用:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.Settings["address"].Value = "new_value";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings"); 

我想它不起作用,因为我没有名为“appSettings”的部分,但是如何访问该“地址”项?我尝试了不同的解决方案,但没有任何效果。

先感谢您。

4

2 回答 2

1

我找到了一个可行的解决方案。读取内存中的整个文件,找到节点,替换值然后覆盖文件。这在我的程序初始化之前在 OnStartup 方法上调用。

XmlDocument doc = new XmlDocument();
doc.Load("MyApp.exe.config");
XmlNodeList endpoints = doc.GetElementsByTagName("endpoint");
foreach (XmlNode item in endpoints)
{
    var adressAttribute = item.Attributes["address"];
    if (!ReferenceEquals(null, adressAttribute))
    {
        adressAttribute.Value = string.Format("net.tcp://{0}:44424/ServerService/", MachineIp);
    }
}
doc.Save("MyApp.exe.config");
于 2012-10-04T06:17:15.040 回答
0

我通常删除密钥并将其添加回来以确保:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.Settings.Remove("address");
        config.AppSettings.Settings.Add("address", "new_value");
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
于 2012-09-27T07:28:11.790 回答