App.config自定義節點讀取

涼生涼憶亦涼心發表於2018-07-23
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!--<otherconfig configSource="XmlConfigother.config" />-->
  <otherconfig   a="1111" b="2222" c="333"/>
</configuration>
public class OtherConfigInfo : ConfigurationSection
    {
        /// <summary>
        /// 獲取配置資訊
        /// </summary>
        /// <returns></returns>
        public static OtherConfigInfo GetConfig()
        {
            return GetConfig("otherconfig");
        }
        /// <summary>
        /// 獲取配置資訊
        /// </summary>
        /// <param name="sectionName">xml節點名稱</param>
        /// <returns></returns>
        public static OtherConfigInfo GetConfig(string sectionName)
        {
            OtherConfigInfo section = (OtherConfigInfo)ConfigurationManager.GetSection(sectionName);
            if (section == null)
                throw new ConfigurationErrorsException("Section " + sectionName + " is not found.");
            return section;
        }

        [ConfigurationProperty("a", IsRequired = false)]
        public string a
        {
            get
            {
                return (string)base["a"];
            }
            set
            {
                base["a"] = value;
            }
        }

        [ConfigurationProperty("b", IsRequired = false)]
        public string b
        {
            get
            {
                return (string)base["b"];
            }
            set
            {
                base["b"] = value;
            }
        }

        [ConfigurationProperty("c", IsRequired = false)]
        public string c
        {
            get
            {
                return (string)base["c"];
            }
            set
            {
                base["c"] = value;
            }
        }
    }

  

 //呼叫方法
OtherConfigInfo configInfo = OtherConfigInfo.GetConfig();
 Console.WriteLine(configInfo.a);

 

相關文章