How to read appSettings section in the web.config

2019-01-13 23:24发布

问题:

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?

回答1:

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

using System.Web.Configuration;

WebConfigurationManager.AppSettings["configFile"]


回答2:

Add namespace

using System.Configuration;

and in place of

ConfigurationSettings.AppSettings

you should use

ConfigurationManager.AppSettings

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


回答3:

ConfigurationManager.AppSettings["configFile"]

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



回答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.



回答5:

    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;
    }