NameValueCollection类读取配置信息

https://blog.51cto.com/u_6725876/5132594

 

C#中的NameValueCollection类读取配置信息,大家可以参考下。   我首先介绍配置文件中的写法: 

1.在VS2015中的工程下建立一个控制台应用程序,其config文件默认名称为App.config,并如下编辑: 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!--NameValueSectionHandler类所在的dll为System.dll,命名空间为System.Configuration-->
<section name="UdpCommConfig" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<UdpCommConfig>
<add key="ListenPath0" value="10.3.10.7" />
<add key="ListenPath1" value="10.3.10.8" />
<add key="ListenPath2" value="10.3.10.9" />
</UdpCommConfig>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.


其中section节点的name值是自己定义的,在此我定义为“UdpCommConfig”,然后添加上方声明的节点,并在节点内部添加两个测试项“<add key="ListenPath0" value="10.3.10.7"/>”等三组需要配置的信息;配置文件定义完毕。 

 

2.打开要读取配置信息的代码文件,添加两个命名空间的引用,分别是: 

using System.Configuration;
using System.Collections.Specialized;
1.
2.


实现需要在​项目-引用​上单击右键-​添加引用​,来添加System.Configuration.dll。而System.Collections.Specialized默认在System.dll,不需要再额外手动添加了。

3.修改控制台应用程序的main函数如下:

static void Main(string[] args)
{
NameValueCollection _table = null;
_table = (NameValueCollection)ConfigurationManager.GetSection("UdpCommConfig");
int count = _table.Count;
string[] listenPath = new string[count];
for (int i=0;i< count; i++)
{
listenPath[i] = _table[i];
}

foreach(string ele in listenPath)
{
Console.WriteLine(ele);
}
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

 


 4、输出结果如下:


-----------------------------------
©著作权归作者所有:来自51CTO博客作者rainbow70626的原创作品,请联系作者获取转载授权,否则将追究法律责任
NameValueCollection类读取配置信息
https://blog.51cto.com/u_6725876/5132594

posted @ 2022-10-10 11:00  vba是最好的语言  阅读(49)  评论(0编辑  收藏  举报