app.configでassemblyBindingをプログラムで変更する方法は?
-
03-07-2019 - |
質問
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構文は次のとおりだと思います:
/ configuration / runtime / assemblyBinding / dependentAssembly / bindingRedirect @ newVersion
(スラッシュが多すぎます)。
またはこれが機能しない場合は、bindingRedirect要素を選択できます(SelectSingleNodeを使用):
/ configuration / runtime / assemblyBinding / dependentAssembly / bindingRedirect
次に、この要素の属性newVersionを変更します。