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

幻夢星雲
发布: 2025-10-25 15:47:02
原创
161人浏览过
答案是通过继承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 的自定义配置节:

<configuration>
  <configSections>
    <section name="mySettings" type="MyApp.MyConfigSection, MyApp" />
  </configSections>
<p><mySettings enabled="true" logPath="C:\logs">
<users>
<add name="admin" role="Admin" />
<add name="guest" role="Guest" />
</users>
</mySettings>
</configuration>
登录后复制

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

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"];  
登录后复制

}

标贝悦读AI配音
标贝悦读AI配音

在线文字转语音软件-专业的配音网站

标贝悦读AI配音20
查看详情 标贝悦读AI配音

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配置节的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号