配置文件是用来存储相关软件的一些信息,如初始化的信息,初始路径,账号,变量等等。方便程序的移植与扩展。
二、配置文件里一般放什么?
配置文件里放程序启动时需要对程序进行配置的信息,比如我们平时启动刚安装的一款软件时,会出现一些填写注册信息的控件,并询问您是否要勾选记住密码、下次自动登录等的复选框(比如QQ、微信),这些注册信息就被写进了相应程序的配置文件里,当程序下次在启动时就会自动读取配置文件,对程序进行配置,这样我们就不用每次都填写这些注册信息,程序就会自启动了。
三、我们为什么要使用配置文件?
将一些可能变动的参数放到配置文件中,可以使程序更加灵活,适应多种业务的场景,我们动态加载的控件参数就可以写在配置文件中,这样当我们更改需求时,我们可以不动代码,只改配置文件就可以了。这样可以大大减少我们的工作难度,提高工作效率。
四、配置文件中都包含哪些部分,如何对配置文件进行分组取值?
配置文件是由配置节组成,我们经常见过的是appSettings配置节,那么当appSettings配置节中的内容太多,我们想要再进行分组要如何进行呢?
System.Configuration中有三个类
System.Configuration.SingleTagSectionHandler
System.Configuration.DictionarySectionHandler
System.Configuration.NameValueSectionHandler
这三个类可以让我们实现自定义配置节,可以大大方便我们对配置文件的读取,使我们的程序更加灵活多变。
①、SingleTagSectionHandler类
配置文件中的代码:
-
<!--自定义配置节:SingleTagSectionHandler-->
-
<configSections>
-
<section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>
-
</configSections>
-
<Test1 setting1="hello" setting2="World"/>
main函数中的代码:
-
NameValueCollection nc = (NameValueCollection)ConfigurationSettings.GetConfig(
"Test");
-
MessageBox.Show(nc.AllKeys[
0].ToString() +
" " + nc[
"Hello"]);
输出的结果为“Hello World”
该类的MSDN讲解:
②、DictionarySectionHandler类
配置文件中的代码:
-
<!--自定义配置节:type DictionarySectionHandler-->
-
<!--此类实现IConfigSectionHandler接口,属性有两个key,value-->
-
<configSections>
-
<section name="Software" type="System.Configuration.DictionarySectionHandler"/>
-
</configSections>
-
<Software>
-
<add key="Hello" value="World"/>
-
</Software>
main函数中的代码:
-
IDictionary IDSoftware = (IDictionary)ConfigurationSettings.GetConfig(
"Software");
-
string[] keys =
new
string[IDSoftware.Keys.Count];
-
string[] values =
new
string[IDSoftware.Values.Count];
-
IDSoftware.Keys.CopyTo(keys,
0);
-
IDSoftware.Values.CopyTo(values,
0);
-
MessageBox.Show(keys[
0] +
" " + values[
0]);
输出的结果为“Hello World”
该类的MSDN讲解:
③、NameValueSectionHandler类
配置文件中的代码:
-
<!--自定义配置节1:type NameValueSectionHandeler是System.configuration中的类提供配置节中的名称/值对配置信息-->
-
<!--此类实现IConfigSectionHandler接口,属性有两个key,value-->
-
<configSections>
-
<section name="Test" type="System.Configuration.NameValueSectionHandler"/>
-
<configSections>
-
<Test>
-
<add key="Hello" value="World"/>
-
</Test>
main函数中的代码:
-
IDictionary IDTest1 = (IDictionary)ConfigurationSettings.GetConfig(
"Test1");
-
string str = (
string)IDTest1[
"setting1"] +
" " + (
string)IDTest1[
"setting2"];
-
MessageBox.Show(str);
输出的结果为“Hello World”
该类的MSDN讲解: