.NET之如何获取App.config配置文件中的参数值

王朝学院·作者佚名  2016-05-21
窄屏简体版  字體: 小  |  中  |  大  |  超大  

.NET之如何获取App.config配置文件中的参数值首先的添加System.Configuration引用类文件中必须有 using System.Configuration;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(); }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航