how to update assemblyBinding section in config file at runtime?

RuntimeSection of the config file update at runtime using this code:

private void ModifyRuntimeAppConfig()
{
  XmlDocument modifiedRuntimeSection = GetResource("Framework35Rebinding");

  if(modifiedRuntimeSection != null)
  {
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    ConfigurationSection assemblyBindingSection = config.Sections["runtime"];

    assemblyBindingSection.SectionInformation.SetRawXml(modifiedRuntimeSection.InnerXml);
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("runtime");
  }
}

with Framework35Rebinding containing:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
      <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="3.5.0.0"/>
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.CompactFramework.Build.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
      <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="9.0.0.0"/>
    </dependentAssembly>
  </assemblyBinding>
</runtime>

and an app.config containing (before the execution of the program):

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
  <runtime>
  </runtime>
</configuration>

Nevertheless it doesn't work for that I wanna do because assemblyBinding is only read at startup of the application whereas the RefreshSection("runtime")


The best way I've found to dynamically bind to a different version of an assembly is to hook the AppDomain.AssemblyResolve event. This event is fired whenever the runtime is unable to locate the exact assembly that the application was linked against, and it allows you to provide another assembly, that you load yourself, in its place (as long as it is compatible).

For example, you can put in a static constructor on your application's main class that hooks the event like this:

using System.Reflection;

static Program()
{
    AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
    {
        AssemblyName requestedName = new AssemblyName(e.Name);

        if (requestedName.Name == "AssemblyNameToRedirect")
        {
            // Put code here to load whatever version of the assembly you actually have

            return Assembly.LoadFrom("RedirectedAssembly.DLL");
        }
        else
        {
            return null;
        }
    };
}

This method avoids the need to deal with the assembly bindings in configuration files and is a bit more flexible in terms of what you can do with it.