title: How to programmatically modify web.config in ASP.NET MVC and C# application?
body: <p>This is my <code>global.asax.cs</code> file in my ASP.NET MVC application. I want to programmatically modify an attribute in <code>web.config</code>. But this error occurred:</p>
  
  <blockquote>
    <p>An error occurred executing the configuration section handler for system.web/roleManager.</p>
  </blockquote>
  
  <p>Code:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Configuration;
  using System.Linq;
  using System.Web;
  using System.Web.Configuration;
  using System.Web.Http;
  using System.Web.Mvc;
  using System.Web.Optimization;
  using System.Web.Routing;
  
  namespace MyApp
  {    
      public class MvcApplication : System.Web.HttpApplication
      {
          protected void Application_Start()
          {
              AreaRegistration.RegisterAllAreas();
              WebApiConfig.Register(GlobalConfiguration.Configuration);
  
              FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
              RouteConfig.RegisterRoutes(RouteTable.Routes);
  
              BundleConfig.RegisterBundles(BundleTable.Bundles);
              AuthConfig.RegisterAuth();
  
              UsingRoleManagerSection.test();
          }
      }
  
      public static class UsingRoleManagerSection
      {
          public static void test()
          {
              try
              {
                  // Set the path of the config file.
                  string configPath = "/Web.config";
  
                  // Get the Web application configuration object.
                  Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
  
                  SystemWebSectionGroup web = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
  
  
                  web.ForceDeclaration(true);
                  web.RoleManager.Enabled = true; 
                  web.RoleManager.SectionInformation.ForceSave = true;              
                  config.Save(ConfigurationSaveMode.Modified);
              }
              catch (Exception ex)
              {
  
              }
          }
      }
  }
  </code></pre>
  
  <p>The <code>RoleManager.SectionInformation.IsLocked</code> is true. I did try to change it to false by set:</p>
  
  <pre><code>configSection.SectionInformation.AllowDefinition = ConfigurationAllowDefinition.Everywhere;
  configSection.SectionInformation.AllowOverride = true;
  </code></pre>
  
  <p>but in first line this error occurred:</p>
  
  <blockquote>
    <p>ConfigurationSection properties cannot be edited when locked.</p>
  </blockquote>