我需要能夠以編程方式更新我的配置文件並更改我的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");
此代碼執行,沒有例外,但不進行任何更改。另外,我在索引端點和服務時遇到了麻煩。有沒有簡單的方法來找到它?使用名稱作爲索引器似乎不起作用。
謝謝!
西格
謝謝馬克。有趣的是,通過ide運行並不能反映這些變化。我考慮的越多,爲什麼這是有道理的,雖然它有點混亂,因爲我正在查看app.config與exe.config的變化。 – Sieg 2010-03-04 20:23:32
@Sieg:那是我最初的直覺之一 - 你在看正確的文件嗎?我注意到,執行代碼時,被修改的實際上是'YourAppName.vshost.exe.config',但即使這些更改實際上並沒有因爲一些不明確的原因而被持久保存到磁盤.... – 2010-03-04 22:07:19