需要使用数组从配置文件中检索值
本文关键字:配置文件 检索 数组 | 更新日期: 2023-09-27 17:49:30
我有一个静态类,它具有应用配置文件中键的自动属性的静态变量。我需要将配置文件中的值分配给使用for循环/contains功能的变量
statics class sample
{
public static string key1
{ get; set; }
}
——注意我现在没有访问代码的权限,所以我不能把它贴在这里
我尝试从配置文件循环的值,但我需要我的代码工作,像检查键从配置文件到类文件中的变量,并在配置文件值分配该值到变量
您可以尝试下面的代码。请注意,我没有运行这段代码。您可能需要稍微调整一下,但这应该允许您遍历类中的属性。
public static class Configs
{
public static string Key1 {get;set;}
public static string Key2 {get;set;}
public static void Main()
{
var info = typeof(Configs).GetProperties();
var appSettings = ConfigurationManager.AppSettings;
foreach(var s in info)
{
Console.WriteLine(s.Name);
foreach (var key in appSettings.AllKeys)
{
if(key == s.Name)
{
s = appSettings[key];
}
}
}
}
}
i got the output: did it as below
Config file
<configuration>
<!--<configSections>
<section name="QuerySettings" type="System.Configuration.NameValueSectionHandler"/>
<section name="QuerySettings" type="CustomConfigApp.ConfigHelper, CustomConfigApp"/>
</configSections>
<QuerySettings>
<add key="Qry1" value="Select * from table" />
<add key="Qry2" value="delete from table" />
</QuerySettings>-->
<appSettings>
<add key="Qry1" value="Select * from table" />
<add key="Qry2" value="delete from table" />
</appSettings>
</configuration>
class file
class sample
{
public string Qry1
{ get; set; }
public string Qry2
{ get; set; }
}
sample s1 = new sample();
var QueryConfigKey = ConfigurationManager.AppSettings;S
if (QueryConfigKey != null)
{
foreach (var serverKey in QueryConfigKey.AllKeys)
{
string serverValue = QueryConfigKey.GetValues(serverKey).FirstOrDefault();
//Console.WriteLine(serverValue);
PropertyInfo propertyInfo = s1.GetType().GetProperty(serverKey);
propertyInfo.SetValue(s1, Convert.ChangeType(serverValue, propertyInfo.PropertyType),null);
}
}
string query1 = s1.Qry1;
string query2 = s1.Qry2;
Console.WriteLine(query1);
Console.WriteLine(query2);`enter code here`
Console.ReadLine();