作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
考虑:
行:
<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/
我是一名优秀的程序员,十分优秀!