转载
https://www.cnblogs.com/lxshwyan/p/10828305.html
如果使用了configSection节点,则configSection必须位于根节点的第0个。App.config中代码如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="CustomerSingleConfig" type="ConfiguraDemo.CustomerSingleConfig,ConfiguraDemo"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<CustomerSingleConfig PlatChName="监控平台系统" PlatEnName="Monitoring platform system"></CustomerSingleConfig>
</configuration>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConfiguraDemo
{
public class CustomerSingleConfig : ConfigurationSection
{
/// <summary>
/// 获取配置信息
/// </summary>
/// <returns></returns>
public static CustomerSingleConfig GetConfig()
{
return GetConfig("CustomerSingleConfig");
}
private static CustomerSingleConfig GetConfig(string sectionName)
{
try
{
CustomerSingleConfig section = (CustomerSingleConfig)ConfigurationManager.GetSection(sectionName);
if (section == null)
throw new ConfigurationErrorsException("Section " + sectionName + " is not found.");
return section;
}
catch (Exception ex)
{
throw new ConfigurationErrorsException("Section " + ex.Message);
}
} /// <summary>
/// 平台中文名称
/// </summary>
[ConfigurationProperty("PlatChName", DefaultValue = "", IsRequired = true, IsKey = false)]
public string PlatChineseName
{
get { return (string)this["PlatChName"]; }
set { this["PlatChName"] = value; }
}
/// <summary>
/// 平台英文名称
/// </summary>
[ConfigurationProperty("PlatEnName", DefaultValue = "", IsRequired = true, IsKey = false)]
public string PlatEnglishName
{
get { return (string)this["PlatEnName"]; }
set { this["PlatEnName"] = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConfiguraDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("---------------------单级配置节点测试-----------------");
Console.WriteLine("PlatChName:" + CustomerSingleConfig.GetConfig().PlatChineseName);
Console.WriteLine("PlatEnName:" + CustomerSingleConfig.GetConfig().PlatEnglishName);
Console.ReadKey();
}
}
}
输出结果
---------------------单级配置节点测试-----------------
PlatChName:监控平台系统
PlatEnName:Monitoring platform system
继承ConfigurationSection需要添加System.Configuration引用