NameValueCollection类读取配置信息

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>

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

 

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

using System.Configuration; 
using System.Collections.Specialized; 

实现需要在项目-引用上单击右键-添加引用,来添加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);
            }
        }

 

 4、输出结果如下:

 Demo下载地址: https://pan.baidu.com/s/19peyXX_W7PimgFPi3pOEJw 提取码: bw5a

posted @ 2019-03-11 20:48  rainbow70626  阅读(209)  评论(0编辑  收藏  举报