Click here to Skip to main content
13,398,905 members (36,846 online)
Click here to Skip to main content
Add your own
alternative version


55 bookmarked
Posted 3 May 2007

Edit and Encrypt Web.Config Sections Using C# 2.0

, 3 May 2007
Rate this:
Please Sign up or sign in to vote.
An article to illustrate editing and encrypting of sections of a Web.Config file programatically.

Screenshot - WebConfigApp.jpg


ASP.NET 1.x allowed configurations in the Web.Config file to be read from a .NET application. But there were no options to manipulate Web.Config contents programmatically. To achieve this, we had to consider the Web.Config file as a normal file or an XML file and manually do it. .NET 2.0 fills this gap and provides many other useful operations to be carried out on the Web.Config file, like editing and encrypting sections of the Web.Config file. This articles illustrates these functionalities via a sample ASP.NET application.

Using the code

The classes and methods to take control of the Web.Config file span across two namespaces:

  1. System.Configuration
  2. System.Web.Configuration

Each section in the Web.Config file has a corresponding class in either of the namespace. These classes allow modification of the corresponding sections. The classes for sections within the "system.web" section are found in System.Web.Configuration. Classes for other sections that are not specific to Web.Config are found in System.Configuration.

Steps to modify a section in Web.Config

  1. Open Web.Config for editing using the WebConfigurationManager class.
  2. Using the respective Configuration class, bring about the necessary changes.
  3. Save changes to the physical file using the Configuration class.
private void UpdateConfig(string strKey, string strValue)
    Configuration objConfig = 
    AppSettingsSection objAppsettings = 
    if (objAppsettings != null)
        objAppsettings.Settings[strKey].Value = strValue;

In the above piece of code, the OpenWebConfiguration() method of the WebConfigurationManager class opens the Web.Config file in the root directory and returns it as a Configuration object. The GetSection() method of the Configuration class accepts a path to a specific section as the argument. The path is the relative path from the root node "configuration". You can refer to deeper nodes (sections in our context) by their names separated by '/'. For example, to get access to the "authentication" section, provide "system.web/authentication" as the parameter to the GetSection() method. It returns a generic ConfigurationSecton object, which can be typecast to the proper configuration section class. In our example, we get hold of the "appSettings" section with the help of the AppSettingsSection class. The AppSettingsSection class instance has a Settings collection property which contains the application setting from the configuration section as key-value pairs. The Settings property can be indexed using a key to get the corresponding value. You can also set the value property and call the Save() method of the Configuration object to write configurations in the Configuration instance to the config file.

To delete an entry in the Web.config file

The Remove() method of the Settings collection deletes an entry from the Configuration instance. The Remove() method accepts the key of the entry to be deleted.

Note: Please do not forget to call the Save() method of the Configuration instance to get the changes reflected in the physical file.


To iterate through all the key-value pairs in a configuration section, access the string array of keys via the AllKeys property of the Settings collection.

foreach (string strKey in objAppsettings.Settings.AllKeys)
    DataRow dr = dt.NewRow();
    dr["Key"] = strKey;
    dr["Value"] = objConfig.AppSettings.Settings[strKey].Value;

Encrypting sections in the Web.Config file

Now comes the security issues. At times there comes the necessity for protecting sections of the config file. In .NET 2.0, there are options available to encrypt sections of the Web.config file programmatically. The following method encrypts the "appSettings" section in the Web.config file.

private void EncryptAppSettings()  
    Configuration objConfig = 
    AppSettingsSection objAppsettings = 
    if (!objAppsettings.SectionInformation.IsProtected)
        objAppsettings.SectionInformation.ForceSave = true;

The code above opens the Web.Config file for modification. It then retrieves the "appSettings" section. The ProtectSection() method of the SectionInformation class marks the configuration section for protection. It accepts the name of the protection provider to be used for the encryption. The ForceSave property indicates if the specified configuration section will be saved even if it has not been modified. Finally, the Save() of the Configuration object writes the configuration settings to the Web.Config file. The argument to the Save() method indicates only properties modified need to be written to the physical file.

Below is a listing of the "appSettings" section before encryption:

Screenshot - WebConfig.jpg

The encrypted "appSettings" section is listed below:

Screenshot - WebConfigEncrypted.jpg

Decrypting sections of the web.config file through code is very identical. The UnprotectSection() method of the SectionInformation class removes the encryption from the configuration section.

private void DecryptAppSettings()
    Configuration objConfig = 
    AppSettingsSection objAppsettings = 
    if (objAppsettings.SectionInformation.IsProtected)
        objAppsettings.SectionInformation.ForceSave = true;

This encryption and decryption functionality can be applied to other sections of the web.config file. It comes in use mostly for the connectionStrings section where usually the user name and password would be specified. This can done by creating a ConfigurationSection object. An example for the connectionStrings section is shown below.

ConfigurationSection objConfigSection = objConfig.ConnectionStrings;

The ConfigurationSection class represents a section within the configuration file. The Configuration class has properties for each configuration section. This property can be used to get the respective ConfigurationSection objects. This is an alternative to the usage of the GetSection() method of the Configuration class.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mohammed Habeeb
Web Developer
India India
Mohammed Habeeb works as a software developer for an IT company in Dubai. He holds a bachelors in Computer Science Engineering from MES College, Calicut University. He is also a Microsoft Certified Application Developer (MCAD) in .NET Framework. He has a strong inclination towards Microsoft technologies especially the .NET Platform. He has been an active member of Cochin and Bangalore Microsoft user groups.
He has a strong passion for science and technology. His interests span through travelling, driving, photography, stamps and coin collection.
You can find more about him @

You may also be interested in...


Comments and Discussions

GeneralA unique article Pin
Sayed Sajid28-Jul-09 2:40
memberSayed Sajid28-Jul-09 2:40 
GeneralEncrypt just 1 key Pin
Millan_Mosh5-Nov-07 9:33
memberMillan_Mosh5-Nov-07 9:33 
GeneralProfile Pin
paul_beckett4-May-07 23:34
memberpaul_beckett4-May-07 23:34 
GeneralSecurity issue Pin
Stefan Prodan4-May-07 1:53
memberStefan Prodan4-May-07 1:53 
GeneralRe: Security issue Pin
phase6417-May-07 15:14
memberphase6417-May-07 15:14 
AnswerRe: Security issue Pin
Mohammed. Habeeb17-May-07 23:54
memberMohammed. Habeeb17-May-07 23:54 
GeneralRe: Security issue Pin
phase6419-May-07 17:19
memberphase6419-May-07 17:19 
GeneralRe: Security issue Pin
DummyDUmb18-Oct-07 13:41
memberDummyDUmb18-Oct-07 13:41 
AnswerRe: Security issue Pin
Mohammed. Habeeb17-May-07 23:40
memberMohammed. Habeeb17-May-07 23:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180218.2 | Last Updated 3 May 2007
Article Copyright 2007 by Mohammed Habeeb
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid