2010-03-04 58 views
3

我需要能夠以編程方式更新我的配置文件並更改我的WCF設置。我一直在嘗試使用我在網上找到的一些示例在一些測試代碼中執行此操作,但是無法獲取配置文件以反映對端點地址的更改。編寫WCF編程配置更改時出現問題

配置(片段):

<!-- Sync Support --> 
    <service name="Server.ServerImpl" 
      behaviorConfiguration="syncServiceBehavior"> 

    <host> 
     <baseAddresses> 
     <add baseAddress="http://localhost:8000/SyncServerHarness"/> 
     </baseAddresses> 
    </host> 

    <endpoint name="syncEndPoint" 
       address="http://localhost:8000/SyncServerHarness/Sync" 
       binding="basicHttpBinding" 
       contract="Server.IServer" /> 

    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 

    </service> 

代碼:

Configuration config = ConfigurationManager.OpenExeConfiguration 
         (ConfigurationUserLevel.None); 

ServiceModelSectionGroup section = (ServiceModelSectionGroup) 
            config.SectionGroups["system.serviceModel"]; 

foreach (ServiceElement svc in section.Services.Services) 
{ 
    foreach (ServiceEndpointElement ep in svc.Endpoints) 
    { 
     if (ep.Name == "syncEndPoint") 
     { 
      ep.Address = new Uri("http://192.168.0.1:8000/whateverService"); 

     } 
    } 
} 

config.Save(ConfigurationSaveMode.Full); 
ConfigurationManager.RefreshSection("system.serviceModel"); 

此代碼執行,沒有例外,但不進行任何更改。另外,我在索引端點和服務時遇到了麻煩。有沒有簡單的方法來找到它?使用名稱作爲索引器似乎不起作用。

謝謝!

西格

回答

2

我改變了兩件事情,和它的作品對我蠻好:

1)我使用OpenExeConfiguration與裝配路徑

2)我訪問<services>部分,而不是<system.serviceModel>節組

有了這兩個更改,一切正常:

Configuration config = ConfigurationManager.OpenExeConfiguration 
         (Assembly.GetExecutingAssembly().Location); 

ServicesSection section = config.GetSection("system.serviceModel/services") 
          as ServicesSection; 

foreach (ServiceElement svc in section.Services) 
{ 
    foreach (ServiceEndpointElement ep in svc.Endpoints) 
    { 
     if (ep.Name == "syncEndPoint") 
     { 
      ep.Address = new Uri("http://192.168.0.1:8000/whateverService"); 
     } 
    } 
} 

config.Save(ConfigurationSaveMode.Full); 
+0

謝謝馬克。有趣的是,通過ide運行並不能反映這些變化。我考慮的越多,爲什麼這是有道理的,雖然它有點混亂,因爲我正在查看app.config與exe.config的變化。 – Sieg 2010-03-04 20:23:32

+0

@Sieg:那是我最初的直覺之一 - 你在看正確的文件嗎?我注意到,執行代碼時,被修改的實際上是'YourAppName.vshost.exe.config',但即使這些更改實際上並沒有因爲一些不明確的原因而被持久保存到磁盤.... – 2010-03-04 22:07:19

1

以防萬一......如果你有調用RefreshSection方法後,沒有更新的app.config一些奇怪的魔法,確保您這樣稱呼它在原崗位:

ConfigurationManager.RefreshSection("system.serviceModel"); 

這樣它永遠不會工作。該呼叫被忽略並通過。相反,這樣稱呼它:

ConfigurationManager.RefreshSection("system.serviceModel/client"); 

您必須指定一個部分(客戶綁定行爲 ...)。如果你需要更新整個配置,那麼遍歷一個循環中的所有部分。 MSDN對此保持沉默。我花了3天的時間尋找這個垃圾。

相關問題