2012-09-27 100 views
1

我有具有以下app.config文件一个WCF服务器:C#更新的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”部分,但如何访问“地址”项?我尝试了不同的解决方案,但没有任何效果

预先感谢您。

+2

我想这是一样的http://stackoverflow.com/questions/966323/how-to-programatically-modify-wcf-app-config-endpoint-address-setting – Fred

回答

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"); 
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"); 
+0

好,但这并不工作,因为我不使用名为“AppSettings”的部分。这是一个自定义部分。 – alexandrudicu