Snippet: Construct WCF Binding from string (xml)

Here is a snippet to convert a bindingconfiguration xml fragment into a Binding (with a few limitations).

Configuration configSystem = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var bindingSection = BindingsSection.GetSection(configSystem);
string customConfig = "<netTcpBinding><binding name=\"netTcpBinding\" maxReceivedMessageSize=\"12345\" hostNameComparisonMode=\"Exact\" /></netTcpBinding>";
// another example: 
// string customConfig = "<binding name=\"basicHttpBinding\" messageEncoding=\"Mtom\" maxReceivedMessageSize=\"14000\" allowCookies=\"True\" /></basicHttpBinding>";
bindingSection.SectionInformation.SetRawXml(string.Format ("<bindings>{0}</bindings>",customConfig));
BindingCollectionElement bindingCollectionElement = null;
foreach (BindingCollectionElement bicoelem in bindingSection.BindingCollections)
{
    if (0 < bicoelem.ConfiguredBindings.Count)
    {
        bindingCollectionElement = bicoelem;
        break;
    }
}
var newBinding = (Binding)bindingCollectionElement.BindingType.Assembly.CreateInstance(bindingCollectionElement.BindingType.FullName);
IBindingConfigurationElement bEleEx = bindingCollectionElement.ConfiguredBindings[0];
bEleEx.ApplyConfiguration(newBinding);

At this point the newBinding is configured with the configurationoptions you added in the "customConfig" string.

HTH