从配置文件中读取密钥
本文关键字:密钥 读取 配置文件 | 更新日期: 2023-09-27 17:52:12
我有一个配置文件,其中包含:
<add key="x36_key1" value="D1"/>
<add key="x36_key2" value="D2"/>
<add key="x36_key3" value="D3"/>
<add key="x36_key4" value="D4"/>
<add key="x36_key5" value="D5"/>
现在我需要这些键在这里使用:
case Keys.D1:
//something happens here
break;
case Keys.D2:
//something happens here
break;
case Keys.D3:
//something happens here
break;
case Keys.D4:
//something happens here
break;
case Keys.D5:
//something happens here
break;
我从每个键中提取值的方式如下:
string key1 = System.Configuration.ConfigurationManager.AppSettings["x36_key1"];
但是因为它是一个字符串,所以不能用作键。
我如何使代码读取在配置文件中定义的键?
您应该将字符串解析为enum Keys
(msdn):
string key1 = System.Configuration.ConfigurationManager.AppSettings["x36_key1"];
Keys key;
if (Enum.TryParse<Keys>(key1, out key))
{
switch (key)
{
case Keys.D1:
//something happens here
break;
case Keys.D2:
//something happens here
break;
case Keys.D3:
//something happens here
break;
case Keys.D4:
//something happens here
break;
case Keys.D5:
//something happens here
break;
}
}
string key1 = System.Configuration.ConfigurationManager.AppSettings["x36_key1"];
Keys k1 = (Keys)Enum.Parse(typeof(Keys), key1);
更新
使用enums .Parse()将配置中的字符串解析为Keys
enum:
var keyFromConfiguration = System.Configuration.ConfigurationManager.AppSettings["x36_key1"];
Keys key = (Keys) Enum.Parse(typeof(Keys), keyFromConfiguration);
switch (key)
{
case Keys.D1:
//something happens here
break;
case Keys.D2:
//something happens here
break;
case Keys.D3:
//something happens here
break;
case Keys.D4:
//something happens here
break;
case Keys.D5:
//something happens here
break;
}