如何获取App.config配置文件中的参数值-创新互联
如何获取App.config配置文件中的参数值?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

首先添加System.Configuration引用
向App.config配置文件添加参数
App.config添加
向App.config配置文件添加参数
例子:
在这个App.config配置文件中,我添加了4个参数,App.config参数类似HashTable都是键/值对
那如何访问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 theKeys = new List(); //保存Key的集合
List theValues = new List(); //保存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();
} 
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联网站建设公司,的支持。
本文题目:如何获取App.config配置文件中的参数值-创新互联
网页路径:http://www.jxjierui.cn/article/digsgs.html


咨询
建站咨询
