从 app.config c# 中读取所有键值
Read all key values from app.config c#
您好,我有以下 app.config 文件
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="DayTime" value="08-20" />
<add key="NightTime" value="20-08" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
<add key="GridMode" value="1"/>
</appSettings>
我需要一次读取所有密钥并将其存储在 Dictionary
之类的地方。
我尝试了以下代码,但给我 null
值
有例外Cannot convert Keyvalueinternalcollection to hashtable
var section = ConfigurationManager.GetSection("appSettings") as Hashtable;
如何读取所有键及其值?
不要转换为 Hashtable
,而是转换为 IEnumerable
:
var section = ConfigurationManager.GetSection("appSettings");
foreach (var kvp in section as IEnumerable)
{
//TODO
}
我想你可以这样做:
var loc=(NameValueCollection)ConfigurationSettings.GetSection("appSettings");
var dic=new Dictionary<string,string>();
foreach (var element in loc.AllKeys)
{
dic.Add(element, loc[k]);
}
var section = ConfigurationManager.GetSection("appSettings")
应该足够了。
哈希表版本。
Hashtable table = new Hashtable((from key in System.Configuration.ConfigurationManager.AppSettings.Keys.Cast<string>()
let value= System.Configuration.ConfigurationManager.AppSettings[key]
select new { key, value }).ToDictionary(x => x.key, x => x.value));
评论其他答案
System.Configuration.ConfigurationManager.AppSettings
是预定义的 'appSettings' 部分,使用它。
您好,我有以下 app.config 文件
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="DayTime" value="08-20" />
<add key="NightTime" value="20-08" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
<add key="GridMode" value="1"/>
</appSettings>
我需要一次读取所有密钥并将其存储在 Dictionary
之类的地方。
我尝试了以下代码,但给我 null
值
有例外Cannot convert Keyvalueinternalcollection to hashtable
var section = ConfigurationManager.GetSection("appSettings") as Hashtable;
如何读取所有键及其值?
不要转换为 Hashtable
,而是转换为 IEnumerable
:
var section = ConfigurationManager.GetSection("appSettings");
foreach (var kvp in section as IEnumerable)
{
//TODO
}
我想你可以这样做:
var loc=(NameValueCollection)ConfigurationSettings.GetSection("appSettings");
var dic=new Dictionary<string,string>();
foreach (var element in loc.AllKeys)
{
dic.Add(element, loc[k]);
}
var section = ConfigurationManager.GetSection("appSettings")
应该足够了。
哈希表版本。
Hashtable table = new Hashtable((from key in System.Configuration.ConfigurationManager.AppSettings.Keys.Cast<string>()
let value= System.Configuration.ConfigurationManager.AppSettings[key]
select new { key, value }).ToDictionary(x => x.key, x => x.value));
评论其他答案
System.Configuration.ConfigurationManager.AppSettings
是预定义的 'appSettings' 部分,使用它。