Saving changes to web.config using System.Configuration.ConfigurationSection


April 2019


287 time


I have created a custom web config section that I can read and modify successfully at runtime. However, it does not physically change the web.config. If the site is restarted or the pool is recycled I lose my changes and it reverts to the original web.config settings.

I would like to be able to persist the changes to the web.config file and I have not been able to figure this out.

My web.config section looks like this:


<MyCustomConfig Address="" 

Here is my configuration class

namespace MyProject.Configuration
    public class MyCustomConfig : System.Configuration.ConfigurationSection
        // Static accessor
        public static MyCustomConfig Current =

        public void Save()
            if (IsModified())
                // I'm getting here, but can't figure out how to save



        public override bool IsReadOnly()
            return false;


        [ConfigurationProperty("OrgId", DefaultValue = "test", IsRequired = true)]
        public string OrgId
            get { return this["OrgId"].ToString(); }
            set { 
                this["OrgId"] = value; 
        [ConfigurationProperty("Address", DefaultValue="", IsRequired=true)]
        public string Address {
            get { return this["Address"].ToString();  }
            set { this["Address"] = value; }

        [ConfigurationProperty("User", DefaultValue = "", IsRequired = true)]
        public string User
            get {
                if (this["User"] == null) return string.Empty;
                else return this["User"].ToString(); 
            set { this["User"] = value; }

In my controller, I modify the settings with the posted form

public ActionResult Edit(ConfigurationViewModel config)

    if (ModelState.IsValid)
        // write changes to web.config
        Configuration.MyCustomConfig.Current.Address = config.SIPAddress;
        Configuration.MyCustomConfig.Current.User = config.User;
        Configuration.MyCustomConfig.Current.OrgId = config.OrgId;

In the config class save method, IsModified() returns true, now I just need to get those modifications to file.

1 answers


Why would you want to make changes to the configuration file at runtime? This would cause an application pool recycle every time the change is made to the file.

Would it make sense to store these settings in a database and restore them from the db upon start of the application?

I'm simply questioning from a best practices point of view, as I know it's possible, just not recommended.