如何在C#控制台程序中配置app.config自定义节?遇异常求助
完整实现步骤
1. 定义配置实体类
创建对应配置节点的强类型类,继承ConfigurationSection(根节点)和ConfigurationElement(子节点):
using System.Configuration; // 子节点ApiSettings的配置类 public class ApiSettings : ConfigurationElement { [ConfigurationProperty("BaseUrl", IsRequired = true)] public string BaseUrl { get => (string)this["BaseUrl"]; set => this["BaseUrl"] = value; } [ConfigurationProperty("EndPoint", IsRequired = true)] public string EndPoint { get => (string)this["EndPoint"]; set => this["EndPoint"] = value; } [ConfigurationProperty("PollingIntervalInSeconds", IsRequired = true, DefaultValue = 10)] public int PollingIntervalInSeconds { get => (int)this["PollingIntervalInSeconds"]; set => this["PollingIntervalInSeconds"] = value; } } // 根节点Configurations的配置类 public class ConfigurationsSection : ConfigurationSection { [ConfigurationProperty("ApiSettings", IsRequired = true)] public ApiSettings ApiSettings { get => (ApiSettings)this["ApiSettings"]; set => this["ApiSettings"] = value; } // 静态方法简化配置读取 public static ConfigurationsSection GetConfig() { var section = (ConfigurationsSection)ConfigurationManager.GetSection("Configurations"); return section ?? throw new ConfigurationErrorsException("无法加载Configurations配置节"); } }
2. 配置app.config
必须先在<configSections>中注册自定义节,否则会抛出配置异常,完整配置如下:
<configuration> <!-- 注册自定义配置节,必须放在所有配置节点之前 --> <configSections> <section name="Configurations" type="你的命名空间.ConfigurationsSection, 你的程序集名称" /> </configSections> <!-- 自定义配置内容 --> <Configurations> <ApiSettings> <BaseUrl>http://localhost:62954</BaseUrl> <EndPoint>api/token</EndPoint> <PollingIntervalInSeconds>10</PollingIntervalInSeconds> </ApiSettings> </Configurations> </configuration>
注意:
type属性需替换为实际的命名空间+类名和程序集名称(程序集名称通常是你的控制台项目名称)。
3. 读取配置
在控制台代码中调用静态方法读取配置:
class Program { static void Main(string[] args) { var config = ConfigurationsSection.GetConfig(); Console.WriteLine($"BaseUrl: {config.ApiSettings.BaseUrl}"); Console.WriteLine($"EndPoint: {config.ApiSettings.EndPoint}"); Console.WriteLine($"轮询间隔: {config.ApiSettings.PollingIntervalInSeconds}秒"); } }
常见异常及修复方案
异常:ConfigurationErrorsException「未找到名为‘Configurations’的节」
修复:检查app.config是否添加了<configSections>节点,确认name与自定义节名称完全一致,type中的命名空间、程序集名与实际代码匹配。异常:ConfigurationErrorsException「无法创建类型‘xxx’的实例」
修复:确保配置类是public访问修饰符,继承关系正确(根节点继承ConfigurationSection,子节点继承ConfigurationElement),且类存在默认无参构造函数(无需手动定义,编译器自动生成)。异常:ConfigurationErrorsException「属性‘xxx’是必需的」
修复:要么在app.config中补全对应的配置节点,要么在ConfigurationProperty特性中设置IsRequired=false,或者指定DefaultValue。类型转换异常(如将字符串转为int失败)
修复:确保app.config中的配置值与类中属性类型匹配,比如PollingIntervalInSeconds是int类型,配置值不能是字母或非数字字符。
内容的提问来源于stack exchange,提问作者Velkumar

