app.config 配置多项 配置集合 自定义配置

2023-05-07,,

C#程序的配置文件,使用的最多的是appSettings 下的<add key="Interval" value="30"/>,这种配置单项的很方便,但是配置集合就不方便了(当然你可以用逗号分隔,key=key1,key2,key3……但是你还是不知道有多少个集合).现在给出解决方案.

需求:程序超级管理员采用这种设置方式,在app.config中配置的方式,可以配置多个.登陆成功后,读取config,看我是不是超级管理员.
(当然,这个需求是很扯淡的,因为我是为了举例子,编造的,哇哈哈哈)

1.下载ConfigurationSectionDesigner_2.0.1.7.vsix,安装;
2.重新打开VS,新建测试工程WindowsFormsApplication2;
3.在工程上右键,添加新建项,选在ConfigurateSectionDesiger,命名为ConfigurateSectionDesiger1;
4.双击ConfigurateSectionDesiger1,打开他的设计页面,点击"工具箱";
5.拖一个Configuration Section到页面上,命名为UserSection;
6.点击UserSection的Elements,新增Element,命名为Users
7.工具箱拖一个ConfigurationElementCollection到页面,命名为UserCollection;
8.点击UserSection中的User的属性,选择Type 为: UserCollection,此时UserSection和UserCollection出现箭头连接;
9.工具箱,拖动一个Configuration Element,命名为User.为User增加Attributes,ID,Name,Gender,Pwd,并指定每个attributes的type为string,将ID的Is key 设置为true.
10.设置UserCollection的Item Type为User.
11.查看ConfigurationSectionDesigner1.csd下,有个文件ConfigurationSectionDesigner1.csd.config
12.打开ConfigurationSectionDesigner1.csd.config,将configSections和userSection标签中的内容复制到App.config的configuration节点中.

<configSections>
<section name="userSection" type="WindowsFormsApplication2.UserSection, WindowsFormsApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>
<userSection xmlns="urn:WindowsFormsApplication2">
<!--
This is just a minimal sample configuration file that shows how to declare
the configuration sections. Because an XML Schema Definition (XSD) is generated for each configuration
section, it should be trivial to edit these files because you have
IntelliSense on the XML definition.
-->
</userSection>

  

13.现在已经配置好了,在app.config中,userSection节点下,敲一下"<",就会出现users的智能提示,在users下敲"<",会出现user的提示,同时user并有iD,Name,Gender,Pwd这些属性
14.读取方法

var section = (UserSection)System.Configuration.ConfigurationManager.GetSection("userSection");
for (int i = 0; i < section.Users.Count; i++)
{
string ID = section.Users[i].ID;
string name = section.Users[i].Name;
string Pwd = section.Users[i].Pwd;
string Gender = section.Users[i].Gender; }

  

注意:app.config中的configSections节点必须放在开始.即是放在configuration节点最开始

PS:这个文章只是利用工具插件,自动生成结构,然后靠在app.config里面配置反射,其实工具那段是可以通过编码来实现的.参看下个文章.

app.config 配置多项 配置集合 自定义配置的相关教程结束。

《app.config 配置多项 配置集合 自定义配置.doc》

下载本文的Word格式文档,以方便收藏与打印。