Wix安装程序修改app.config的bindingRedirect newVersion字段报错求助
正确修改app.config中bindingRedirect的newVersion字段
嘿,你猜得太对了!bindingRedirect 绝对不是 assemblyIdentity的子元素——这就是你找不到节点、运行报错的核心原因。先给你理清楚这个配置的正确层级结构,再告诉你手动和代码修改的两种方法:
首先,记住正确的XML层级
bindingRedirect和assemblyIdentity是平级关系,都隶属于dependentAssembly节点,完整的结构应该是这样的:
<configuration> <runtime> <!-- 必须带这个xmlns属性,否则配置不生效也找不到节点! --> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <!-- 描述你要重定向的目标程序集 --> <assemblyIdentity name="YourTargetAssembly" publicKeyToken="123456789abcdef" culture="neutral" /> <!-- 和assemblyIdentity平级,这才是正确的位置 --> <bindingRedirect oldVersion="0.0.0.0-1.5.0.0" newVersion="2.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
方法1:手动修改配置文件
如果只是临时调整,按下面的步骤来:
- 打开你的app.config,找到
<configuration>节点 - 如果没有
<runtime>节点,就在<configuration>下面新建一个 - 在
<runtime>里添加/找到<assemblyBinding>,一定要带上那个xmlns属性,这是很多人踩坑的点 - 找到对应程序集的
<dependentAssembly>节点(通过assemblyIdentity的name、publicKeyToken匹配) - 确保
<bindingRedirect>和<assemblyIdentity>平级,直接修改它的newVersion属性值就好
方法2:用代码自动修改(适合你的安装程序场景)
既然你是开发安装程序,肯定需要自动修改配置,这里给你一个C#的示例代码(注意处理命名空间,这是关键):
using System.Configuration; using System.Xml; // 替换成你的目标app.config路径 var targetConfigPath = @"C:\YourApp\App.config"; var config = ConfigurationManager.OpenExeConfiguration(targetConfigPath); var runtimeSection = config.GetSection("runtime") as ConfigurationSection; if (runtimeSection != null) { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(runtimeSection.SectionInformation.GetRawXml()); // 必须指定assemblyBinding的命名空间,否则找不到节点 var nsManager = new XmlNamespaceManager(xmlDoc.NameTable); nsManager.AddNamespace("asm", "urn:schemas-microsoft-com:asm.v1"); // 按程序集名称过滤,找到对应的dependentAssembly var targetAssemblies = xmlDoc.SelectNodes( "//asm:dependentAssembly[asm:assemblyIdentity/@name='YourTargetAssembly']", nsManager ); foreach (XmlNode assemblyNode in targetAssemblies) { // 查找已有的bindingRedirect节点 var redirectNode = assemblyNode.SelectSingleNode("asm:bindingRedirect", nsManager); if (redirectNode != null) { // 直接更新newVersion redirectNode.Attributes["newVersion"].Value = "2.0.0.0"; } else { // 如果没有该节点,就创建一个新的 var newRedirect = xmlDoc.CreateElement("bindingRedirect", "urn:schemas-microsoft-com:asm.v1"); newRedirect.SetAttribute("oldVersion", "0.0.0.0-1.5.0.0"); newRedirect.SetAttribute("newVersion", "2.0.0.0"); assemblyNode.AppendChild(newRedirect); } } // 保存修改到配置文件 runtimeSection.SectionInformation.SetRawXml(xmlDoc.OuterXml); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("runtime"); }
几个关键提醒
- 命名空间不能丢:
<assemblyBinding>的xmlns属性是必须的,否则无论是读取还是修改都会找不到节点 - 匹配程序集信息:assemblyIdentity的name、publicKeyToken、culture必须和目标程序集完全一致,否则重定向不会生效
- oldVersion范围:可以指定单个版本(比如
1.0.0.0),也可以指定版本范围(比如0.0.0.0-1.5.0.0)
内容的提问来源于stack exchange,提问作者JWoodley13
相关产品推荐
相关产品推荐

