一、在程序中引入 System.Configuration 程序集
二、xml 的配置如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="user" type="System.Configuration.SingleTagSectionHandler"/>
<section name="sex" type="System.Configuration.DictionarySectionHandler"/>
<section name="age" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<user phone="183****36" address="广州越秀"/>
<sex>
<add key="sex" value="男"/>
</sex>
<age>
<add key="age" value="25"/>
</age>
<appSettings>
<add key="name" value="alpha"/>
<add key="pwd" value="123456"/>
</appSettings>
</configuration>
三、在程序中使用
string username = System.Configuration.ConfigurationManager.AppSettings["name"];
string password = System.COnfiguration.ConfigurationMapper.AppSettings["pwd"];
Console.WriteLine("username:{0}", username);
Console.WriteLine("password:{0}", password);
System.Collections.Hashtable h1 = (System.Collections.Hashtable)System.Configuration.ConfigurationManager.GetSection("user");
string phone = h1["phone"].ToString();
string address = h1["address"].ToString();
Console.WriteLine("phone:{0}", phone);
Console.WriteLine("address{0}", address);
System.Collections.Hashtable h2 = (System.Collections.Hashtable)System.Configuration.ConfigurationManager.GetSection("sex");
string sex = h2["sex"].ToString();
Console.WriteLine("sex:{0}", sex);
System.Collection.Specialized.NameValueCollection h3 = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("age");
string age = h3["age"].ToString();
Console.WriteLine("age:{0}", age);
Console.ReadKey();
如果在配置文件中没有使用 <configSection> 对三个自定义节点\ <user>、<sex>、<age>进行注册,程序在运行的时候会出现如下的错误。