首页 > 代码库 > C# 自定config文件

C# 自定config文件

1、配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="color"   type="System.Configuration.NameValueSectionHandler" />
    <section name="message" type="System.Configuration.DictionarySectionHandler"/>
    <section name="name"   type="System.Configuration.SingleTagSectionHandler"/>
  </configSections>
  <color>
    <add key="red"   value="#ff0000"/>
    <add key="green" value="#00ff00"/>
    <add key="blue"  value="#0000ff"/>
  </color>
  <message>
    <add key="welcome" value="你好,欢迎"/>
  </message>
  <name firstName="陈" lastName="明明"/>
</configuration>

2、代码读取

 1 //get color
 2             NameValueCollection color = (NameValueCollection)ConfigurationManager.GetSection("color");
 3             foreach (String str in color.AllKeys)
 4             {
 5                 Console.WriteLine(str + ":" + color[str]);
 6             }
 7             //get message
 8             IDictionary message = (IDictionary)ConfigurationManager.GetSection("message");
 9             foreach (String str in message.Keys)
10             {
11                 Console.WriteLine(str + ":" + message[str]);
12             }
13             // get name
14             IDictionary name = (IDictionary)ConfigurationManager.GetSection("name");
15             foreach (String str in name.Keys)
16             {
17                 Console.WriteLine(str + ":" + name[str]);
18             }
19             //Console.WriteLine(name["firstName"]);
20             Console.Read();

 

C# 自定config文件