MC+A Stream

Our Blog and News Stream

Changing Appsettings in the Web.Config

October 18th, 2007

Sometimes when creating a new application that will be deployed in multiple locations, it’s necessary to have some globally configurable variables in the web.config file. It’s important to give the users as easy of an experience in installing the application as possible.

We aim to make all of our applications easy to install, configure and use. This following code is the event when the user clicks on the button to change the appSettings in the web.config file.

using System.Web.Configuration;

protected void SettingButton_Click(object sender, EventArgs e)
{
Configuration config;

config = WebConfigurationManager.OpenWebConfiguration(“~”);

AppSettingsSection settingChange;

settingChange = config.GetSection(“appSettings”) as AppSettingsSection;

if (settingChange != null)
{

settingChange.Settings["setting"].Value = setting.Text;

config.Save();

}

}

As you can see, you first need to define what configuration file that you wish to change. In the above example, the first 2 lines of code open the web.config file for the local application. If you wish to configure a different file, change “~” to “folder\config.config” (depending on the location of the file).

The next 2 lines define the AppSettingsSection and in the above example, we are changing values of keys located in the appSettings section. To conclude the event, check if the value entered is null and if it is not, write the new value to the web.config file.

Once IIS realizes that the web.config file has been changed, it should then reset the application and begin to use the new values during runtime.

That’s it! If the web.config file is not updating, check to see if it is read-only or that the username your application is running under has the proper permissions to write to the web.config file.

Comments are closed.