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

在 C# 中读取 app.config 或 web.config 中的自定义 XML 配置节,可以通过继承 ConfigurationSection 类来实现。这种方式结构清晰、类型安全,适合处理复杂的配置结构。
假设你的 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"]; }
使用 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}");
} }
基本上就这些,只要结构定义清楚,读取自定义 XML 配置节就很方便。
以上就是C# 如何读取app.config或web.config中的xml配置节的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号