C# 如何读取app.config或web.config中的xml配置节

答案是通过继承ConfigurationSection类可实现C#中读取自定义配置节。首先定义UserElement、UserCollection和MyConfigSection类映射XML结构,接着在config文件中声明configSections及mySettings节,然后使用ConfigurationManager.GetSection(“mySettings”)获取实例并读取Enabled、LogPath及Users集合信息,最后注意configSections顺序、程序集名称匹配和文件部署问题。

c# 如何读取app.config或web.config中的xml配置节

在 C# 中读取 app.config 或 web.config 中的自定义 XML 配置节,可以通过继承 ConfigurationSection 类来实现。这种方式结构清晰、类型安全,适合处理复杂的配置结构。

1. 定义配置节结构

假设你的 config 文件中有一个名为 mySettings 的自定义配置节:

      

你需要创建一个类来映射这个结构:

public class UserElement : ConfigurationElement
{
[ConfigurationProperty(“name”, IsRequired = true)]
public string Name => (string)this[“name”];

[ConfigurationProperty("role", IsRequired = true)]  public string Role => (string)this["role"];  

}

public class UserCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement() => new UserElement();

protected override object GetElementKey(ConfigurationElement element) => ((UserElement)element).Name;  

}

public class MyConfigSection : ConfigurationSection
{
[ConfigurationProperty(“enabled”, DefaultValue = false)]
public bool Enabled => (bool)this[“enabled”];

[ConfigurationProperty("logPath", DefaultValue = "")]  public string LogPath => (string)this["logPath"];  [ConfigurationProperty("users")]  public UserCollection Users => (UserCollection)this["users"];  

}

2. 在代码中读取配置

使用 ConfigurationManager.GetSection 方法获取配置节:

var section = ConfigurationManager.GetSection(“mySettings”) as MyConfigSection;

if (section != null)
{
Console.WriteLine($”Enabled: {section.Enabled}”);
Console.WriteLine($”LogPath: {section.LogPath}”);

foreach (UserElement user in section.Users)  {      Console.WriteLine($"User: {user.Name}, Role: {user.Role}");  }  

}

3. 注意事项

确保 configSections 声明在其他配置节之前。type 属性中的程序集名称(如 MyApp)要与实际输出程序集一致。若在 ASP.NET 项目中使用 web.config,引用 System.Configuration 并确保 DLL 正确部署。调试时可检查 config 文件是否被正确复制到输出目录。

基本上就这些,只要结构定义清楚,读取自定义 XML 配置节就很方便。

以上就是C# 如何读取app.config或web.config中的xml配置节的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1440932.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 17:35:08
下一篇 2025年12月17日 17:35:26

相关推荐

发表回复

登录后才能评论
关注微信