获取App.config配置文件中的各个参数值
来源: 阅读:1590 次 日期:2015-08-13 15:49:31
温馨提示: 小编为您整理了“获取App.config配置文件中的各个参数值”,方便广大网友查阅!

这篇文章介绍了获取app.config配置文件中的参数值方法,首先是要添加System.Configuration引用,其次类文件中必须有 using System.Configuration;再次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();

}

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

更多信息请查看IT技术专栏

更多信息请查看 网络编程
由于各方面情况的不断调整与变化, 提供的所有考试信息和咨询回复仅供参考,敬请考生以权威部门公布的正式信息和咨询为准!

2026上岸·考公考编培训报班

  • 报班类型
  • 姓名
  • 手机号
关于我们| 联系我们| 人才招聘| 网站声明| 网站帮助| 非正式的简要咨询| 简要咨询须知| 新媒体/短视频平台| 手机站点| 投诉建议
工业和信息化部备案号:滇ICP备2023014141号-1 云南省教育厅备案号:云教ICP备0901021 滇公网安备53010202001879号 人力资源服务许可证:(云)人服证字(2023)第0102001523号
云南网警备案专用图标
联系电话:0871-65099533/13759567129 获取招聘考试信息及咨询关注公众号:
咨询QQ:1093837350(9:00—18:00) 版权所有:
云南网警报警专用图标
Baidu
map