如何阅读web.config文件中的appSettings部分?


92

我的XML看起来像这样,文件名是 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>

在代码中,我这样读

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

我得到一个空值。没有异常被抛出。这是正确的方法吗?

Answers:


154

由于您正在访问a,因此web.config您可能应该使用

using System.Web.Configuration;

WebConfigurationManager.AppSettings["configFile"]

29

添加名称空间

using System.Configuration;

并代替

ConfigurationSettings.AppSettings

你应该使用

ConfigurationManager.AppSettings

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


4

您应该添加System.configuration dll作为参考并使用 System.Configuration.ConfigurationManager.AppSettings["configFile"].ToString

不要忘了using在开始时添加语句。希望会有所帮助。


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;
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.