ARTICLE

Add Key and Values to the Web.config File Dynamically in ASP.NET

Posted by Rajendra Taradale Articles | ASP.NET Programming November 30, 2011
This article will help you add Key and Values dynamically to a web.config file.
Reader Level:
Download Files:
 

This article will help you add the Key and Value to the web.config file dynamically.

This is simple and useful application for those who wants dynamic changes in the web.config file. The sample source code allows you to change the key and value pair. There is
no need to open web.config file. The application also allows you to update and delete the key/value pair.

Before you start any operation, you need to select one of the option buttons - Add, Update, or Delete.

Let's have to UI design Home Page.

Step 1:

The UI for adding a new key/value looks like following:

WebConfig1.gif

For updating the previous tag, Just select the Key values from Dropdown and update the new values with previous one

WebConfig2.gif

For Delete Operation, select the Key from dropdown which you want delete.

WebConfig3.gif

WebConfig4.gif

WebConfig5.gif

Step 2:

Please find the Code (.cs)

protected void Add_values(object sender, EventArgs e)
    {
        if (TextBox1.Text == string.Empty && TextBox2.Text==string.Empty)
        {
               //RFC Added
        }
        else
        {
            string Key_c = TextBox1.Text.ToString().Trim();
            string Value_c = TextBox2.Text.ToString().Trim();
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
            webConfigApp.AppSettings.Settings.Add(Key_c, Value_c);
            webConfigApp.Save();
            DisplayConfigTags();
            Label1.Visible = true;
            Response.Redirect("Default.aspx");
        }
    }

protected void update_values(object sender, EventArgs e)
    {

        Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
        string Key_c = KeyList1.SelectedItem.Value;
        string Value_c = TextBox2.Text.ToString();
        webConfigApp.AppSettings.Settings[Key_c].Value = Value_c;
        webConfigApp.Save();
        Label1.Visible = true;
        Response.Redirect("Default.aspx");

        TextBox2.Text = string.Empty;
    }

protected void detele_values(object sender, EventArgs e)
    {
        string Key_c = KeyList1.SelectedItem.Value;
        string Value_c = TextBox2.Text.ToString();
        Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
        webConfigApp.AppSettings.Settings.Remove(Key_c);
        webConfigApp.Save();
        Label1.Visible = true;
        Response.Redirect("Default.aspx");
    }

 

Download the attached source code for more details.

 

COMMENT USING

Trending up