[c#] Read Variable from Web.Config

How can I add and read the value from web.config file?

This question is related to c# .net asp.net web-config

The answer is


Given the following web.config:

<appSettings>
     <add key="ClientId" value="127605460617602"/>
     <add key="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>

Example usage:

using System.Configuration;

string clientId = ConfigurationManager.AppSettings["ClientId"];
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];

If you want the basics, you can access the keys via:

string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();

To access my web config keys I always make a static class in my application. It means I can access them wherever I require and I'm not using the strings all over my application (if it changes in the web config I'd have to go through all the occurrences changing them). Here's a sample:

using System.Configuration;

public static class AppSettingsGet
{    
    public static string myKey
    {
        get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
    }

    public static string imageFolder
    {
        get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
    }

    // I also get my connection string from here
    public static string ConnectionString
    {
       get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
    }
}

Ryan Farley has a great post about this in his blog, including all the reasons why not to write back into web.config files: Writing to Your .NET Application's Config File


Assuming the key is contained inside the <appSettings> node:

ConfigurationSettings.AppSettings["theKey"];

As for "writing" - put simply, dont.

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.


I am siteConfiguration class for calling all my appSetting like this way. I share it if it will help anyone.

add the following code at the "web.config"

<configuration>
   <configSections>
     <!-- some stuff omitted here -->
   </configSections>
   <appSettings>
      <add key="appKeyString" value="abc" />
      <add key="appKeyInt" value="123" />  
   </appSettings>
</configuration>

Now you can define a class for getting all your appSetting value. like this

using System; 
using System.Configuration;
namespace Configuration
{
   public static class SiteConfigurationReader
   {
      public static String appKeyString  //for string type value
      {
         get
         {
            return ConfigurationManager.AppSettings.Get("appKeyString");
         }
      }

      public static Int32 appKeyInt  //to get integer value
      {
         get
         {
            return ConfigurationManager.AppSettings.Get("appKeyInt").ToInteger(true);
         }
      }

      // you can also get the app setting by passing the key
      public static Int32 GetAppSettingsInteger(string keyName)
      {
          try
          {
            return Convert.ToInt32(ConfigurationManager.AppSettings.Get(keyName));
        }
        catch
        {
            return 0;
        }
      }
   }
}

Now add the reference of previous class and to access a key call like bellow

string appKeyStringVal= SiteConfigurationReader.appKeyString;
int appKeyIntVal= SiteConfigurationReader.appKeyInt;
int appKeyStringByPassingKey = SiteConfigurationReader.GetAppSettingsInteger("appKeyInt");

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to web-config

No assembly found containing an OwinStartupAttribute Error IIS Config Error - This configuration section cannot be used at this path How to enable GZIP compression in IIS 7.5 how to set start page in webconfig file in asp.net c# Authentication issue when debugging in VS2013 - iis express Forms authentication timeout vs sessionState timeout Specified argument was out of the range of valid values. Parameter name: site Access-control-allow-origin with multiple domains "An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..." ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d