If you are working with web.config file in any web application you may want to access it using C# code somewhere in your application, so in this article I have provided sample code to read key value from web config file using C# and how to write values in web config file programmtically.

I suppose you are already using Visual Studio with a web-application with web.Config file in it.

So navigate to web.config file of your project and we will be adding few key-values inside <configuration> -> <appsettings> -> key-value , so I have added 2 key-value pairs for demo purpose

<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

   <!--Added these keys in web config -->
    <add key="Key1" value="Value1" />
     <add key="Key2" value="Value2" />

  </appSettings>
<!--Some more code  -->
</configuration>

Read Key value from WebConfig using C#

To read values of "key1" and "key2" using C#, we have the following code

            var val1 = ConfigurationManager.AppSettings["Key1"];
            var val2 = ConfigurationManager.AppSettings["Key2"];

            ViewBag.KeyValue1 = "Key1 =" + val1;
            ViewBag.KeyValue2 = "Key2 =" + val2;

and using namespace "System.Configuration" ( you can add reference to "System.Configuration" by right-clicking on Reference inside your project and inisde "Assemblies" search for "System.Configuration")

So, complete C# MVC Contorller code

using System.Configuration;
using System.Web.Mvc;

namespace WebConfigReadWrite.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var val1 = ConfigurationManager.AppSettings["Key1"];
            var val2 = ConfigurationManager.AppSettings["Key2"];

            ViewBag.KeyValue1 = "Key1 =" + val1;
            ViewBag.KeyValue2 = "Key2 =" + val2;

            return View();
        }
      
    }
}

You can also use it in your View, as we have saved values in ViewBag, so inside your "Views"->"Home"->"Index.cshtml", you can have code like below

@{
    ViewBag.Title = "Home Page";
}
<br />
<div class="row">
    <div class="col-md-4">

        @ViewBag.KeyValue1 <br />
        @ViewBag.KeyValue2 <br />
    </div>

</div>

Once you build and run it in browser, you will output like below

read-web-config-key-asp-net-csharp-min.png

Read Connection string from web-config using C#

Now, one of the most frequently asked or used code in C# is reading connection string from WebConfig file to use it in C# code, for saving data in database or reading data from database.

So, suppose your connection string webconfig file looks like this

  <connectionStrings>
    <add name="ConnecttionStringName" connectionString="Data Source=DESKTOP-12345U\MSSQLSERVER2016;Initial Catalog=Testing;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Suggested: SQL server connection string examples in C# & XML

To use read connection string, we can use the below code C#

    string constring = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constring))
            {
                //do database operations like read table data or save data.
            }

Writing to WebConfig using C#

This is something programmers don't do usually using C# code, but sometimes, we may still need to update key-value in connection string while executing C# code.

So, to update anything in web config, first we will fetch the web config file using it's location path in C#

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

You will have to use namespace "System.Web.Configuration"

Now, suppose you want to add new key in <appSettings> section or want to update/delete keys from this section.

First, we will fetch <appSettings> section in our C# code.

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

The AppSettingsSection contains a settings property that can be used to access the collection of key/value pairs that are in the <appSettings> section in web.config, so we will be using it our C# code

KeyValueConfigurationCollection settings = appSettingsSection.Settings;

Now to Add or Update key-value inside webConfig we can use the below C# code

            //add new key
            settings.Add("Key3", "Value3");

              //update old key value
            settings["Key2"].Value = "Key2 New Update value";

Now, once we are done we can save the settings of webConfig

           //save update webconfig file
            configuration.Save();

Here is the complete code

   //get web config file
            Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");

            //get appSettings section
            AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");

            //get key-value settings
            KeyValueConfigurationCollection settings = appSettingsSection.Settings;

            //add new key
            settings.Add("Key3", "Value3");

            //update old key value
            settings["Key2"].Value = "Key2 New Update value";

            //save update webconfig file
            configuration.Save();

Let's try to run the code in browser and test it you will see output like below Gif image, take a look at before values of appSettings keys and after code is executed.

read-write-web-config-c-sharp

Similarly, to delete any key-value from <appSettings> section, we can use the code below

    settings.Remove("Key1");

    configuration.Save();

That's it, we are done. Hope it was helpful, If you have any questions regarding the above post, feel free to use the below comments section.