How to read appSettings section in the web.config file?
Asked Answered
S

7

107

My XML looks like this and the filename is web.config

<?xml version="1.0"?>
<configuration>
  <appSettings>   
    <add key="configFile" value="IIS.config"/>
    <add key="RialtoDomain" value="ASNC_AUDITORS"/>    
  </appSettings>
  <system.serviceModel>
    ....
  </system.serviceModel>
</configuration>

In the code when I read like this

String path = ConfigurationSettings.AppSettings["configFile"];

I am getting a null value. No exception is thrown. Is this the right way to do it?

Slender answered 16/11, 2011 at 5:40 Comment(1)
You can also read web.config appSettings values directly from an .aspx page #4153342Fariss
G
168

Since you're accessing a web.config you should probably use

using System.Web.Configuration;

WebConfigurationManager.AppSettings["configFile"]
Guzman answered 16/11, 2011 at 6:1 Comment(1)
I have deployed a .net 6 webapi on iis. Should I use app settings file or web config file for settings?Imaginary
V
34

Add namespace

using System.Configuration;

and in place of

ConfigurationSettings.AppSettings

you should use

ConfigurationManager.AppSettings

String path = ConfigurationManager.AppSettings["configFile"];
Vintager answered 16/11, 2011 at 5:53 Comment(0)
S
7
ConfigurationManager.AppSettings["configFile"]

http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx

Steven answered 16/11, 2011 at 5:44 Comment(1)
I checked that still i am getting a null value. I checked the spelling of the key and everything.Slender
A
4

You should add System.configuration dll as reference and use System.Configuration.ConfigurationManager.AppSettings["configFile"].ToString

Don't forget to add usingstatement at the beginning. Hope it will help.

Ashtonashtonunderlyne answered 5/6, 2013 at 21:58 Comment(0)
M
0
    using System.Configuration;

    /// <summary>
    /// For read one setting
    /// </summary>
    /// <param name="key">Key correspondent a your setting</param>
    /// <returns>Return the String contains the value to setting</returns>
    public string ReadSetting(string key)
    {
        var appSettings = ConfigurationManager.AppSettings;
        return appSettings[key] ?? string.Empty;
    }

    /// <summary>
    /// Read all settings for output Dictionary<string,string> 
    /// </summary>        
    /// <returns>Return the Dictionary<string,string> contains all settings</returns>
    public Dictionary<string, string> ReadAllSettings()
    {
        var result = new Dictionary<string, string>();
        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            result.Add(key, ConfigurationManager.AppSettings[key]);
        return result;
    }
Musette answered 26/2, 2018 at 14:58 Comment(0)
D
0

Here's the easy way to get access to the web.config settings anywhere in your C# project.

 Properties.Settings.Default

Use case:

litBodyText.Text = Properties.Settings.Default.BodyText;
litFootText.Text = Properties.Settings.Default.FooterText;
litHeadText.Text = Properties.Settings.Default.HeaderText;

Web.config file:

  <applicationSettings>
    <myWebSite.Properties.Settings> 
      <setting name="BodyText" serializeAs="String">
        <value>
          &lt;h1&gt;Hello World&lt;/h1&gt;
          &lt;p&gt;
      Ipsum Lorem
          &lt;/p&gt;
        </value>
      </setting>
      <setting name="HeaderText" serializeAs="String">
      My header text
        <value />
      </setting>
      <setting name="FooterText" serializeAs="String">
      My footer text
        <value />
      </setting>
    </myWebSite.Properties.Settings>
  </applicationSettings>

No need for special routines - everything is right there already. I'm surprised that no one has this answer for the best way to read settings from your web.config file.

Defenestration answered 25/10, 2020 at 1:0 Comment(0)
E
0

You can also convert your appSetting section to a variable that you can inject in any constructors.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="MyValue1" value="MyString"
        <add key="MyValue2" value="600"
        <add key="MyValue3" value="https://stackoverflow.com/"
    </appSettings>
</configuration>

Declare an class as bellow:

public class AppSettings 
{
    public string MyValue1 { get; set; }
    public int MyValue2 { get; set; }
    public Uri MyValue3 { get; set;}
}

Declare the extension function ToVariable() in a new static class as bellow:

    public static class ObjectExtension
    {
        public static T ToVariable<T>(this object data) where T : class, new()
        {
            if (data is NameValueCollection dataCollection)
            {
                var target = new T();
                var targetProperties = target.GetType()?.GetProperties() ;

                foreach(string key in dataCollection.AllKeys)
                {
                    var property = targetProperties.FirstOrDefault(x => x.Name.Equals(key, System.StringComparison.InvariantCultureIgnoreCase));
                    if (property != null)
                    {
                        switch (Type.GetTypeCode(property.PropertyType))
                        {
                            case TypeCode.String:
                                property.SetValue(target, dataCollection[key], null);
                                break;
                            case TypeCode.Int32:
                                property.SetValue(target, Int32.Parse(dataCollection[key].ToString()), null);
                                break;
                            case TypeCode.Object:
                                switch (property.PropertyType.Name)
                                {
                                    case nameof(Uri):
                                        property.SetValue(target, new Uri(dataCollection[key].ToString()), null);
                                        break;
                                    default: throw new NotImplementedException($"The Object type [{property.PropertyType.Name}] is not implemented for the property [{property.Name}]");
                                }
                                break;
                            default:
                                throw new NotImplementedException($"The Type [{property.PropertyType}] is not implemented for the property [{property.Name}]");
                        }
                    }
                }
                return target;
            }
            return default(T);
        }
    }

And finally you can use it in your Global.asax or OWIN Startup class as bellow:

var appSettings = ConfigurationManager.GetSection("appSettings").ToVariable<AppSettings>();
Egad answered 9/2, 2024 at 8:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.