Andrew Taylor's Blog

How to save changes to your web.config appSettings section

by Andrew Taylor on Feb.06, 2010, under ASP.NET Programming

From time to time you may need to be able to save settings to your web.config file. Yesterday I had a need to do this, and I thought I would check the internet and see if I could find any good examples of how to save settings back to the web.config file.

After viewing the first couple dozen entries, I found one thing in common. Most of the ideas were either “don’t do it” or very complex without the need to be.

The fact is that there are many times when you may want to save changes to your web.Config or other config files. Most open source applications for example save settings to a config file rather than a database file. This makes it easier for people to make changes to the config file without direct access to the database. Perfect case in point is this WordPress Blog which has a config file.

So today I want to show you in just 5 lines of code, how you can save a setting back to your appSettings section of your web.config file.

//Save to Existing Key
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

AppSettingsSection appSettings = config.AppSettings;

appSettings.Settings["UserName"].Value = txtUsername.Text;

config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings");

And there you have it, 5 lines of very uncomplex code, and we’ve saved a value back to our appSettings section of our web.Config file.

In this case the appSettings collection that we have defined works like any standard collection, I can do appSettings.Settings.Add(Key, Value) to add a new key, I can remove, I can clear, etc.

Of course you will need to make sure that your IIS User has write permissions to the folder for this to work properly.

  • Share/Bookmark
:, ,

1 Comment for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...