2012-09-27 50 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