ConfigurationManager.GetSection()方法的使用


GetSection方法讀取的是configSections節點,這個節點在web.config配置文件中,它比較特殊,必須放置於首節點,也就是說,在它之前不能有其它類型的節點。configSections子節點有section和sectionGroup,后者是前者的集合節點:

<configSections>
    <section name="CustomConfig" type="OrderMvc.CustomConfig, OrderMvc"/>
</configSections>

 

web.config關於CustomConfig的定義:

  <CustomConfig>
    <Name Value="asdf"/>
  </CustomConfig>

 

下面說說它的作用,通過對ConfigurationManager.GetSection(...)方法的調用,如果某個類繼承IConfigurationSectionHandler接口,那么會觸發此接口的Create方法,這樣我們就可以做一些事了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Xml;

namespace OrderMvc
{
    public class CustomConfig : IConfigurationSectionHandler
    {
        public string Name { get; private set; }
        public object Create(object parent, object configContext, XmlNode section)
        {
            CustomConfig config = new CustomConfig();
            var name = section.SelectSingleNode("Name");
            if (name != null && name.Attributes != null)
            {
                var attribute = name.Attributes["Value"];
                if (attribute != null)
                    config.Name = attribute.Value;
            }
            return config;
        }
    }
}

 

調用:

var config = ConfigurationManager.GetSection("CustomConfig") as CustomConfig;
            Debug.WriteLine(config.Name);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM