c# - .NET 配置文件 : How to check if ConfigSection is present

标签 c# .net

考虑:

行:

<section name="unity" />

block :

<unity>
    <typeAliases />
    <containers />
</unity>

假设该行在 .config 文件中可用,而该 block 丢失。

如何以编程方式检查 block 是否存在?

[编辑]

对于那些迅速将问题标记为否定的天才们:

我已经试过了ConfigurationManager.GetSection()

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

var section = config.GetSection("unity");

var sInfo = section.SectionInformation;

var isDeclared = sInfo.IsDeclared;

如果我弄错了,请纠正我,如果 <configSections>,上面不会返回null已定义(即使缺少实际的统一 block )。

最佳答案

由于 ConfigurationSection 继承自 ConfigurationElement,您可以使用 ElementInformation 属性来判断反序列化后是否找到实际元素。

使用此方法检测配置文件中是否缺少ConfigurationSection元素:

//After Deserialization
if(customSection.ElementInformation.IsPresent == false)
    Console.WriteLine("Section Missing");

要确定某个元素是否丢失,您可以使用该部分中的属性(假设它称为“propName”),获取 propName 的 ElementInformation 属性并检查 IsPresent标志:

if(customSection.propName.ElementInformation.IsPresent == false)
    Console.WriteLine("Configuration Element was not found.");

   

当然如果你想检查是否缺少定义,使用下面的方法:

CustomSection mySection = 
    config.GetSection("MySection") as CustomSection;

if(mySection is null)
    Console.WriteLine("ConfigSection 'MySection' was not defined.");

-希望这有帮助

关于c# - .NET 配置文件 : How to check if ConfigSection is present,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23430938/

相关文章:

c# - WPF:使用复选框绑定(bind)命令

c# - 在包含固定数组的托管不安全结构上,C# 'fixed' 语句的开销是多少?

.net - Azure 媒体服务 : Get the duration of a video that needs to be encoded

c# - 如何在 .NET 的 Windows 窗体中打开新窗口?

c# - 嵌套开关表达式

c# - 我必须定义每个运算符(operator)吗?

c# - Minecraft 1.6.2 自定义启动器

c# - 在并行循环中使用 SMO 从 .net 中的 SQL Server 数据库编写对象定义脚本

c# - 在 C# 中读取 excel 2003(.xls)

c# - Convert.ToDouble() 抛出格式异常