10

我试图通过使用 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 也无权访问此部分。

4

3 回答 3

10

我找到了我需要的东西。XmlNamespaceManager 是必需的,因为 assemblyBinding 节点包含 xmlns 属性。我修改了代码以使用它并且它可以工作:

    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"));
    }
于 2009-05-01T00:04:56.480 回答
8

听起来您现在已经对配置文件进行了调整,但我认为您可能仍然对如何在运行时调整绑定重定向感兴趣。关键是要使用AppDomain.AssemblyResolve事件,详情在这个答案中。我更喜欢它而不是使用配置文件,因为我的版本号比较可能更复杂一些,而且我不必在每次构建期间调整配置文件。

于 2010-02-26T20:40:53.080 回答
-1

我认为正确的 Xpath 语法是:

/configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect@newVersion

(你的斜线太多了)。

或者,如果这不起作用,您可以选择 bindingRedirect 元素(使用 SelectSingleNode):

/configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect

然后修改这个元素的属性newVersion。

于 2009-04-30T22:30:08.470 回答