esa*_*sac 10 c# xml configuration xmldocument configuration-files
我试图通过使用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>
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用以下代码将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"));
}
Run Code Online (Sandbox Code Playgroud)
但是,它会引发"未找到"的异常.如果我将路径备份到/ configuration/runtime它就可以了.但是,一旦我添加了assemblyBinding,它就找不到该节点.可能这与xmlns有关吗?知道怎么修改这个吗?ConfigurationManager也无权访问此部分.
esa*_*sac 10
我找到了我需要的东西.由于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"));
}
Run Code Online (Sandbox Code Playgroud)
听起来像是你有你的配置文件调整现在的工作,但我想你可能仍然感兴趣的是如何在运行时调整绑定重定向.关键是使用AppDomain.AssemblyResolve事件,详细信息在此答案中.我更喜欢使用配置文件,因为我的版本号比较可能会更复杂,我不必在每次构建期间调整配置文件.
| 归档时间: |
|
| 查看次数: |
11714 次 |
| 最近记录: |