从配置文件中读取内容,可以使用以下方法:

配置文件以下边为准

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="mygroup">
      <section name="mysection"   type="CLRSecondTests.ConfigSection,CLRSecondTests"/>
      <section name="color"  type="System.Configuration.NameValueSectionHandler" />
    </sectionGroup>
  </configSections>
  <mygroup>
    <color>
      <add key="red"   value="#ff0000"/>
      <add key="green" value="#00ff00"/>
      <add key="blue"  value="#0000ff"/>
    </color>
    <mysection  user="test" password="test123">
      <element element1="属性1" element2="属性2"></element>
    </mysection>
  </mygroup>
</configuration>

 

方法一:

  public void Test2()
        {
            NameValueCollection color = (NameValueCollection)ConfigurationManager.GetSection("mygroup/color");
            foreach (String str in color.AllKeys)
            {
                Console.WriteLine($"str :{color[str]}");
            }
        }

 

 


其中,color配置节的路径要正确,它在组mygroup下,所以,完整的相对路径应该是mygroup/color。 

然后通过configurationManager获取之后,获取到的是键值对,在配置文件中的类型中要写正确:<section name="color"  type="System.Configuration.NameValueSectionHandler" />

 

然后就可以使用了

方法二:自定义与配置文件结构相同的类型

    public class ConfigSection : ConfigurationSection
    {
        public ConfigSection()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        [ConfigurationProperty("user", DefaultValue = "yanghong", IsRequired = true)]
        public string User
        {
            get { return (string)this["user"]; }
            set { this["user"] = value; }
        }

        [ConfigurationProperty("password", DefaultValue = "password", IsRequired = true)]
        public string PassWord
        {
            get { return (string)this["password"]; }
            set { this["password"] = value; }
        }

        [ConfigurationProperty("element")]
        public elementinfo Element
        {
            get { return (elementinfo)this["element"]; }
            set { this["element"] = value; }
        }
    }
    public class elementinfo : ConfigurationElement
    {
        public elementinfo() { }


        [ConfigurationProperty("element1", DefaultValue = "element1", IsRequired = true)]
        public string Element1
        {
            get { return (string)this["element1"]; }
        }

        [ConfigurationProperty("element2", DefaultValue = "element2", IsRequired = true)]
        public string Element2
        {
            get { return (string)this["element2"]; }
        }


    }

 

要注意的是:

自定义类型,类要从ConfigurationSection派生

然后定义的属性要贴上属性标签,同时,内嵌的类型也要定义完整,

 

使用时,可以直接获取配置节,转换为自定义类型:

public void Test1()
        {
            ConfigSection config = (ConfigSection)ConfigurationManager.GetSection("mygroup/mysection");
            Console.Write($"用户名:{ config.User.ToString() }密码:{config.PassWord} 元素属性:{config.Element.Element1} {config.Element.Element2}");
        }

 


  

posted on 2020-11-12 10:44  梅桦  阅读(284)  评论(0编辑  收藏  举报