Programmatically manipulating web.config in ASP.NET 2.0 and ASP.NET 3.5

Posted by: Suprotim Agarwal , on 1/30/2008, in Category ASP.NET
Views: 201001
Abstract: At times, we feel the need to manipulate the web.config file programmatically at run time. ASP.NET 2.0 provides an API to do so in an elegant manner. The API’s are contained in the System.Configuration and System.Web.Configuration namespaces. In this article, we will be exploring how to view and edit the web.config programatically using this API.
Programmatically manipulating web.config in ASP.NET 2.0 and ASP.NET 3.5
 
ASP.NET provides the Web Site Administration Tool to view and manage the configuration settings for your ASP.NET website. These configuration settings are stored in an xml file called web.config.
“web.config is an application configuration file used to define configuration settings such as connecting strings, authentication, authorization etc., for an ASP.NET application
The tool provides an easy to use interface to edit the configuration settings. However this tool works well when you have to manually make changes. At times, there could be a possibility where we need to make changes to the web.config at runtime. For example: a user requesting to control the connecting string, change session timeouts and so on.
For this purpose, ASP.NET provides the Configuration API to programmatically manipulate the configuration settings in web.config. The API’s are contained in the System.Configuration and System.Web.Configuration namespaces. In fact, internally the Web Site Administration Tool uses the same API to edit configuration settings.
The WebConfigurationManager class in the System.Web.Configuration namespace is used to create a Configuration object. This object is used to read and write changes to the web.config file. Let us walk through a small example to understand how we can use the API to edit the configuration settings.
Step 1: Create a new website. Add a web.config file to your website (Right Click project > Add New Item > Web Configuration File. Keep the default name as Web.config and click Add).
Step 2: Make the following changes to your web.config
In your <system.web> tag, uncomment the <customError> tag. We will be reading and editing one of the attributes of this tag. The end result after removing the comments should be as shown below:
<authenticationmode="Windows" />
        <!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.        -->
 
        <customErrorsmode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <errorstatusCode="403"redirect="NoAccess.htm" />
            <errorstatusCode="404"redirect="FileNotFound.htm" />
        </customErrors>
 
    </system.web>
Step 3: We will now go ahead and make changes to the ‘defaultRedirect’ attribute of the <customErrors> tag, using the API we just discussed. For this purpose, add a textbox, label control and a button to the form. After adding the controls, the source view of Default.aspx would look similar to the following:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblErrorPage" runat="server" Text="Rename Error Page to :"></asp:Label>
        <asp:TextBox ID="txtError" runat="server"></asp:TextBox><br />
        <br />
        <asp:Button ID="btnRename" runat="server" Text="Rename" /></div>
    </form>
</body>
</html>
The textbox will be used to display the default value of the ‘defaultRedirect’ attribute.
Step 4: In the Page_Load, display the current default value of the ‘defaultRedirect‘ attribute. To do so, declare the objects for Configuration and WebConfigurationManager at form level and add the following code at Form_Load():
C#
Configuration configuration;
CustomErrorsSection section;
 
protected void Page_Load(object sender, EventArgs e)
{
        configuration = WebConfigurationManager.OpenWebConfiguration("~");
        section =            (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
        txtError.Text = section.DefaultRedirect.ToString();
 }
VB.NET
Private configuration As Configuration
Private section As CustomErrorsSection
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      configuration = WebConfigurationManager.OpenWebConfiguration("~")
      section = CType(configuration.GetSection("system.web/customErrors"), CustomErrorsSection)
      txtError.Text = section.DefaultRedirect.ToString()
End Sub
As seen in the code above, an explicit conversion is required to the CustomErrorSection and then the GetSection() is used on the configuration object to read section value into the textbox.
Step 5: If you run the application, the textbox is populated with the default value of the ‘defaultRedirect ‘ attribute. If you haven’t changed the value in the web.config, the value displayed is ‘GenericErrorPage.htm’.
Step 6: Now let us see how to change this value. To do so, we use the same ‘section’ object and set the value on button click.
C#
protected void btnRename_Click(object sender, EventArgs e)
    {
        if (section != null)
        {
            section.DefaultRedirect = "SomePage.htm";
            configuration.Save();
            // display a message informing the user that value has changed
        }
    }
VB.NET

Protected Sub btnRename_Click(ByVal sender As Object, ByVal e As EventArgs)
            If Not section Is Nothing Then
                  section.DefaultRedirect = "SomePage.htm"
                  configuration.Save()
' display a message informing the user that value has changed
            End If
End Sub
Run the code and click on the Rename button. The ‘defaultRedirect’ section is set to a value and the Save() method is called on the configuration object to persist the changes in web.config. If you now open and view the web.config file, the ‘defaultRedirect’ will have a different value, ‘SomePage.htm’
Similarly you can edit other sections as well. You can view the other section classes in the System.Web.Configuration namespaces. Read more about this namespace over here.
As you saw, it is quiet easy to use the Configuration API to view and edit the configuration settings. Just keep in mind that making changes to the web.config restarts the webserver and invalidates the cache. So do not do it often. I would suggest you to try out some samples on your own. For example, edit the connection string or the app settings section in the web.config to a desired value, by exploring the namespaces mentioned in the article and exploring the WebConfigurationManager class.
I hope this article was useful and I thank you for viewing it.

If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Afuan Aria on Tuesday, June 16, 2009 3:13 AM
Following exception occur. Access to the path 'c:\inetpub\wwwroot\webconfigtest\web.config' is denied. How can i solve this??
Comment posted by Suprotim Agarwal on Tuesday, June 16, 2009 11:21 PM
Which OS do you use. If it is Windows Server 2003, make sure your Network Service has rights to access web.config.
Comment posted by Chris on Wednesday, June 17, 2009 1:26 PM
Thank you, just what I was wondering about!
Comment posted by Andrei on Thursday, June 18, 2009 6:21 AM
Invoking WebConfigurationManager.OpenWebConfiguration("~") requires full trust. It's not good for many hosted web applciations.
Comment posted by kamal choudhary on Tuesday, January 26, 2010 4:11 AM
hi sir , this is very helpfull for me and all programmar

Comment posted by Shikha Rav on Monday, March 22, 2010 3:31 AM
Hi, Very guood article, it helpled me a lot. thnx
Comment posted by Sandeep on Saturday, May 15, 2010 5:10 PM
Hi all,

Here is a link that provide a good explanation of how to modify we.config and its affect on the application

http://aspdotnethacker.blogspot.com/2010/05/modify-webconfig-file-at-runtime.html
Comment posted by Girish Kumar on Friday, May 28, 2010 11:04 AM
Thanks man. Really good article.
Comment posted by rsemenu on Tuesday, June 29, 2010 4:01 PM
Hi all,

Here is a link that provide a good explanation of how to modify we.config and its affect on the application

<a href="http://www.a2zmenu.com/CSharp/Modify%20webconfig%20file%20at%20runtime.aspx">http://www.a2zmenu.com/CSharp/Modify%20webconfig%20file%20at%20runtime.aspx</a>
Comment posted by Udayan on Friday, July 2, 2010 1:46 PM
XML Webpad - http://xmlwebpad.codeplex.com/. this is an open source framework, editor and toolkit to view and edit XML files that can also be seamlessly integrated with any web application.
Comment posted by web development on Tuesday, July 6, 2010 9:20 AM
Thanks for such an informative and interesting article here. It is really hard working with ASP.NET for sure. Those people who were not working as web developers in the past are suffering while learning this programming language. I know that because I am one of those people. Such articles as yours really help a lot. They help to understand at least essentials of those programming languages. When you know some simple things - it is easier to learn hard things too. Thanks for the great article one more time and keep publishing them in the nearest future too.
Comment posted by Pablo on Tuesday, January 11, 2011 5:35 PM
Thanks for the post. quick question, can the API be used to update connectionStrings or AppSettings/key ?
THanks,
Pablo
Comment posted by mahesh on Monday, January 24, 2011 5:01 AM
Error:The type or namespace name 'CustomErrorsSection' could not be found (are you missing a using directive or an assembly reference?)      
Comment posted by Eddy Jawed on Wednesday, February 16, 2011 6:42 AM
Thanks a lot - this is a brilliant and useful article. :)
Comment posted by MLN on Friday, October 21, 2011 4:38 AM
An alert message is being displayed as "web.config has been changed from outside environmet.Do u want to reload it..." How to prevent this messagee from being displayed so that it changes can be saved automatically
Comment posted by MLN on Friday, October 21, 2011 4:50 AM
An alert message is being displayed as "web.config has been changed from outside environmet.Do u want to reload it..." How to prevent this messagee from being displayed so that it changes can be saved automatically
Comment posted by MLN on Friday, October 21, 2011 6:04 AM
Hey please help me.
I am able to change the web.config file through above code. But after config.save(), while I tried to access the value of a key in appsettings it still retrieving the old .
Eg:<add key ="EXAM" value="ABC"> I have changed the value of "ABC" to "DEF".
str=configuarationmanager.appsetting["EXAM"].value.tostring()
is retrieving the value to be "ABC" before and after config.save()
Comment posted by Parmar Jeeten on Wednesday, April 4, 2012 12:34 PM
What changes i will need to do in web config file ???
Comment posted by Prakash on Friday, May 4, 2012 5:16 AM
Excellent ...that is what i want..
Comment posted by monu on Wednesday, May 8, 2013 9:41 PM
resp sir,

its giving erorr ,config file is read only...

please give the solution
Comment posted by hukam on Wednesday, May 8, 2013 9:48 PM
following error coimg
Failed to map the path '/'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Failed to map the path '/'.

Source Error:


Line 21:     {
Line 22:
Line 23:       con = WebConfigurationManager.OpenWebConfiguration("~/web.config");
Line 24:         cuserr = (CustomErrorsSection)con.GetSection("system.web/customErrors");
Line 25:         TextBox1.Text = cuserr.DefaultRedirect.ToString();

help me plz........
Comment posted by rt on Wednesday, November 13, 2013 2:52 AM
tryry
Comment posted by no access to web.config to network service on Tuesday, February 10, 2015 9:53 AM
Remember to add NETWORK SERVICE account read write access to both your application folder and your web.config file.