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

来源:这里教程网 时间:2026-02-21 17:28:49 作者:

在 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"];  

}

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 配置节就很方便。

相关推荐