How to modify web.config file programmatically ?

Web.config plays an important role when we create web application in ASP.NET. Normally here we store some custom application level settings (like Database Connection String, Mail Server address, etc…). Some of the advantages of keeping values in web.config file are.

1. Easily Readable (As it is in XML file format). 2. Accessible through out our project. 3. Can be modified easily (As stored as Key–Value Pair).

4. No need of recompiling the application after modifying the web.config.

So if we want to change the mail server address or database path tomorrow and if we are storing all these configurations in the web.config then it will be a cake walk for modifying them easily. Moreover you can also create a beautiful UI for the admin so that web.config file can be changed easily from that place itself. Here is how you can modify the web.config file programmatically.

Step 1: Use the namespace of configuration:
using System.Configuration;

Step 2: Get the key value pair of the web config. Which will give you all the key value pairs.

System.Collections.Specialized.NameValueCollection nvcKeys = ConfigurationManager.AppSettings;

    Now you can traverse through the collection and find the keys & values.

Step 3: Modify & store.
Take the Key and store value corresponding to that key.

Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text; // custom value.
myConfiguration.Save();

Step 4: Fetch & Modify Connection String.
Connection string returned as ConnectionStringSettingsCollection . So create ConnectionStringSettingsCollection Object.

ConnectionStringSettingsCollection cssDatabase = ConfigurationManager.ConnectionStrings;
        myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text;

Advantages of Web.Config over storing all these key and values in database are: 1. Faster access.

2. Able to change the database path.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!