如何在app.config中以编程方式修改assemblyBinding?

我试图通过使用XmlDocument类并直接修改值来在安装时更改bindingRedirect元素。 这是我的app.config看起来像:

   ...           ...  

然后我尝试使用以下代码将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")); } 

但是,它会引发“未找到”的exception。 如果我将路径备份到/ 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。