例如:从下面的 wxpay.config 配置文件中获取相关的信息:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="paysection" type="Test.Common.PaymentSection, Test.Common" /> </configSections> <paysection> <pays> <!--微信扫码和公众号支付--> <pay name="WXPAY"> <adds> <!-- 微信订单下载信息" --> <add key="" value="https://api.mch.weixin.qq.com/pay/downloadbill" /> <!-- 下载多少天前的支付订单 --> <add key="" value="1" /> <!-- FTP服务器ip --> <add key="" value="" /> <!-- FTP服务器账号 --> <add key="" value="" /> <!-- FTP服务器密码 --> <add key="" value="" /> <!-- FTP服务器文件保存路径{0}表示订单下载日期 --> <add key="" value="" /> </adds> </pay> </pays> </paysection> </configuration>
处理方法:
string file = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "wxpay.config"); ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = file; var configManager = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); if (configManager.HasFile) { instance = (PaymentSection)configManager.GetSection(paysection); }
PaymentSection 类的代码如下:
public class PaymentSection : ConfigurationSection { internal const string SECTION_NAME = "paysection"; /// <summary> /// 支付配置 /// </summary> [ConfigurationProperty("pays", Options = ConfigurationPropertyOptions.IsRequired)] public PayCollection PaySection { get { return (PayCollection)base["pays"]; } } } /// <summary> /// /// </summary> public class PayCollection : ConfigurationElementCollection { /// <summary> /// /// </summary> public PayCollection() { base.AddElementName = "pay"; } /// <summary> /// /// </summary> /// <returns></returns> protected override ConfigurationElement CreateNewElement() { return new PayElement(); } /// <summary> /// key查询值 /// </summary> /// <param name="key">key</param> /// <returns></returns> public PayElement this[object key] { get { return (PayElement)base.BaseGet(key); } } /// <summary> /// /// </summary> /// <param name="element"></param> /// <returns></returns> protected override object GetElementKey(ConfigurationElement element) { var el = (element as PayElement); return string.Format("{0}", el.Name); } } public class PayElement : ConfigurationElement { /// <summary> /// 元素类型 /// </summary> [ConfigurationProperty("name", IsRequired = true, IsKey = true)] public string Name { get { return (string)base["name"]; } set { base["name"] = value; } } }