当前位置: 移动技术网 > IT编程>开发语言>.net > 获取App.config配置文件中的参数值

获取App.config配置文件中的参数值

2017年12月12日  | 移动技术网IT编程  | 我要评论

csol外挂下载,ss501解散原因,承赤高速招聘

下面通过代码示例给大家展示下,具体内容如下:

首先添加system.configuration引用
向app.config配置文件添加参数

app.config添加
向app.config配置文件添加参数
  例子:

  在这个app.config配置文件中,我添加了4个参数,app.config参数类似hashtable都是键/值对

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <appsettings>
 <add key="thedate" value="2015-07-20 16:25"/>
 <add key="thename" value="alice"/>
 <add key="thetype" value="nba"/>
 <add key="theprice" value="12500.00"/>
 </appsettings>
</configuration>

  那如何访问app.config配置文件中的参数值呢?

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.configuration;

namespace appconfigdemo
{
 class program
 {
  static void main(string[] args)
  {
   //判断app.config配置文件中是否有key(非null)
   if (configurationmanager.appsettings.haskeys())
   {
    //循环遍历出配置文件中的所有的键key
    foreach (string s in configurationmanager.appsettings)
    {
     console.writeline(s);
    }
   }
   console.readkey();
  }
 }
}

  使用for循环遍历key的代码如下:


       

 static void main(string[] args)
  {
   //判断app.config配置文件中是否有key(非null)
   if (configurationmanager.appsettings.haskeys())
   {
    //循环遍历出配置文件中的所有的键key
    for (int i = 0; i < configurationmanager.appsettings.count; i++)
    {
     console.writeline(configurationmanager.appsettings.getkey(i));
    }
   }
   console.readkey();
  }

  通过key访问value的方法:

       

static void main(string[] args)
  {
   //判断app.config配置文件中是否有key(非null)
   if (configurationmanager.appsettings.haskeys())
   {
    //获取“thedate”键的value
    foreach (string s in configurationmanager.appsettings.getvalues("thedate"))
    {
     console.writeline(s);
    }
   }
   console.readkey();
  }

  如果你想获取所有key的value集合,那该怎么办呢?

  思路:将所有的key遍历出后保存在一个容器里(例如:数组),然后用key匹配找出value即可。

       

 static void main(string[] args)
  {
   //判断app.config配置文件中是否有key(非null)
   if (configurationmanager.appsettings.haskeys())
   {
    list<string> thekeys = new list<string>(); //保存key的集合
    list<string> thevalues = new list<string>(); //保存value的集合
    //遍历出所有的key并添加进thekeys集合
    foreach (string thekey in configurationmanager.appsettings.keys)
    {
     thekeys.add(thekey);
    }
    //根据key遍历出所有的value并添加进thevalues集合
    for (int i = 0; i < thekeys.count; i++)
    {
     foreach (string thevalue in configurationmanager.appsettings.getvalues(thekeys[i]))
     {
      thevalues.add(thevalue);
     }
    }
    //验证一下
    console.writeline("*************key*************");
    foreach (string s in thekeys)
    {
     console.writeline(s);
    }
    console.writeline("************value************");
    foreach (var item in thevalues)
    {
     console.writeline(item);
    }
   }
   console.readkey();
  }


以上代码就是使用.net技术获取app.config配置文件中的参数值的例子,有需要的朋友可以参考下。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网