需要使用数组从配置文件中检索值

时间:2015-05-16 05:40:27

标签: c# console

我有一个静态类,其中包含静态变量,其中包含app配置文件中键的自动属性。我需要使用for loop / contains功能将配置文件中的值分配给那些变量

statics class sample
{
  public static string key1
  { get; set; }
}

- 注意我现在无权访问这些代码

我尝试从配置文件中循环这些值,但我需要我的代码才能正常工作,例如检查配置文件中的密钥到类文件中的变量,并将配置文件值中的值分配给变量

2 个答案:

答案 0 :(得分:0)

您可以尝试类似下面的代码。请注意我没有运行此代码。您可能需要稍微调整一下,但这应该允许您在类中迭代属性。

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];
                      }
         }
    }
  }
}

答案 1 :(得分:0)

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();