1

I have a WCF server which has the following app.config file:

<?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>

At installation on a different machine, I want to make it to update automatically the address with the address of that machine. I have the string but I don't understand how to update the "address" item in the app.config file. I have the following code but this does not work:

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

I guess it is not working because I do not have the section named "appSettings", but how to access that "address" item ? I tried different solutions, but nothing works.

Thank you in advance.

Alexandru Dicu
  • 1,151
  • 1
  • 16
  • 24
  • 2
    I think this is the same as http://stackoverflow.com/questions/966323/how-to-programatically-modify-wcf-app-config-endpoint-address-setting – Fred Sep 27 '12 at 07:19

2 Answers2

1

I have found a solution that works. Read the entire file in memory, find the node, replace the value and then overwrite the file. This is called on the OnStartup method, before initialization of my program.

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");
Alexandru Dicu
  • 1,151
  • 1
  • 16
  • 24
0

I usually remove the key and add it back to make sure:

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");
HaemEternal
  • 2,229
  • 6
  • 31
  • 50