How to programmatically modify assemblyBinding in app.config?

陌路散爱 提交于 2019-11-29 09:45:28

I found what I needed. The XmlNamespaceManager is required as the assemblyBinding node contains the xmlns attribute. I modified the code to use this and it works:

    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"));
    }
Don Kirkby

Sounds like you've got your configuration file tweak working now, but I thought you might still be interested in how to adjust binding redirects at run time. The key is to use the AppDomain.AssemblyResolve event, and the details are in this answer. I prefer it over using the configuration file, because my version number comparison can be a bit more sophisticated and I don't have to tweak the configuration file during every build.

I think the right Xpath syntax is:

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

(you have a slash too many).

Or if this doesn't work you could select the bindingRedirect element (using SelectSingleNode):

/configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect

Then modify the attribute newVersion of this element.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!