我的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"];
我得到一个空值。没有异常被抛出。 这是正确的方法吗?
答案 0 :(得分:138)
由于您正在访问web.config
,因此您应该使用
using System.Web.Configuration;
WebConfigurationManager.AppSettings["configFile"]
答案 1 :(得分:28)
添加名称空间
using System.Configuration;
代替
ConfigurationSettings.AppSettings
你应该使用
ConfigurationManager.AppSettings
String path = ConfigurationManager.AppSettings["configFile"];
答案 2 :(得分:6)
ConfigurationManager.AppSettings["configFile"]
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx
答案 3 :(得分:4)
您应该添加System.configuration dll作为参考,并使用System.Configuration.ConfigurationManager.AppSettings["configFile"].ToString
不要忘记在开头添加using
语句。希望它会有所帮助。
答案 4 :(得分: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;
}
答案 5 :(得分:0)
这是在C#项目中任何地方访问web.config设置的简便方法。
Properties.Settings.Default
用例:
litBodyText.Text = Properties.Settings.Default.BodyText;
litFootText.Text = Properties.Settings.Default.FooterText;
litHeadText.Text = Properties.Settings.Default.HeaderText;
Web.config文件:
<applicationSettings>
<myWebSite.Properties.Settings>
<setting name="BodyText" serializeAs="String">
<value>
<h1>Hello World</h1>
<p>
Ipsum Lorem
</p>
</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>
无需特殊例程-一切都已准备就绪。令我惊讶的是,没有人提供从您的web.config文件读取设置的最佳方法的答案。