![](/img/trans.png)
[英]How to programmatically modify WCF app.config endpoint address setting?
[英]How to programmatically modify assemblyBinding in app.config?
我試圖通過使用XmlDocument類並直接修改值來在安裝時更改bindingRedirect元素。 這是我的app.config看起來像:
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
...
</sectionGroup>
</configSections>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MyDll" publicKeyToken="31bfe856bd364e35"/>
<bindingRedirect oldVersion="0.7" newVersion="1.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
...
</configuration>
然后我嘗試使用以下代碼將1.0更改為2.0
private void SetRuntimeBinding(string path, string value)
{
XmlDocument xml = new XmlDocument();
xml.Load(Path.Combine(path, "MyApp.exe.config"));
XmlNode root = xml.DocumentElement;
if (root == null)
{
return;
}
XmlNode node = root.SelectSingleNode("/configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect/@newVersion");
if (node == null)
{
throw (new Exception("not found"));
}
node.Value = value;
xml.Save(Path.Combine(path, "MyApp.exe.config"));
}
但是,它會引發“未找到”的異常。 如果我將路徑備份到/ configuration / runtime它就可以了。 但是,一旦我添加了assemblyBinding,它就找不到該節點。 可能這與xmlns有關嗎? 知道怎么修改這個嗎? ConfigurationManager也無權訪問此部分。
我找到了我需要的東西。 由於assemblyBinding節點包含xmlns屬性,因此需要XmlNamespaceManager。 我修改了代碼以使用它並且它可以工作:
private void SetRuntimeBinding(string path, string value)
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Path.Combine(path, "MyApp.exe.config"));
}
catch (FileNotFoundException)
{
return;
}
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1");
XmlNode root = doc.DocumentElement;
XmlNode node = root.SelectSingleNode("//bindings:bindingRedirect", manager);
if (node == null)
{
throw (new Exception("Invalid Configuration File"));
}
node = node.SelectSingleNode("@newVersion");
if (node == null)
{
throw (new Exception("Invalid Configuration File"));
}
node.Value = value;
doc.Save(Path.Combine(path, "MyApp.exe.config"));
}
聽起來你現在已經調試了配置文件,但我認為你可能仍然對如何在運行時調整綁定重定向感興趣。 關鍵是使用AppDomain.AssemblyResolve事件,詳細信息在此答案中 。 我比使用配置文件更喜歡它,因為我的版本號比較可能更復雜,我不必在每次構建期間調整配置文件。
我認為正確的Xpath語法是:
/配置/運行/ assemblyBinding / dependentAssembly / bindingRedirect @ NEWVERSION
(你的斜線太多了)。
或者,如果這不起作用,您可以選擇bindingRedirect元素(使用SelectSingleNode):
/配置/運行/ assemblyBinding / dependentAssembly / bindingRedirect
然后修改此元素的屬性newVersion。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.