Development

Programming the web.config File Using C#

The Configuration API in ASP.NET 2.0

The configuration API of ASP.NET 2.0 adds a great level of
flexibility in that it allows us to add or edit a configuration file seamlessly
in ASP.NET. The WebConfigurationManager class in the System.Web.Configuration
namespace has the OpenWebConfiguration method that can be used to open the
configuration file of the application as a Configuration object for reading
from or writing to the configuration file. The virtual path to the
configuration file is specified to this method as a parameter. The following
code snippet displays all the keys of the appSettings section of the web.config
file:

 

Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");

 AppSettingsSection
appSettingsSection =

  (AppSettingsSection)configuration.GetSection("appSettings");

 if (appSettingsSection !=
null)

  {

   foreach (string key in
appSettingsSection.Settings.AllKeys)

    {

      Response.Write(key);

    }

  }

 

The following method can be used to modify a specific key —
value pair of the web.config file — programmatically using C#:

 

public void Modify(string key, string value)

{

Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");

AppSettingsSection appSettingsSection =
(AppSettingsSection)configuration.GetSection("appSettings");

   if (appSettingsSection != null)

   {

       appSettingsSection.Settings[key].Value =
value;

       configuration .Save();

   }

}

 

The following method can be used to delete a specific key
in the web.config file programmatically using C#:

 

public void Remove(string key)

{

Configuration configuration =
WebConfigurationManager.OpenWebConfiguration("~");

AppSettingsSection appSettingsSection =
(AppSettingsSection)configuration.GetSection("appSettings");

  if (appSettingsSection
!= null)

  {

     appSettingsSection.Settings.Remove(key);

     configuration .Save();

  }

}

 

Conclusion

Even if modifying a web.config file programmatically can
be a handy solution in some situations, it is not recommended to do so
frequently in a Web application, as any change in the web.config file will restart
the Web server and refresh the cache entries.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s