c# - 如何识别缺少的 ConfigurationElement?

标签 c# .net configuration configurationmanager

使用 System.Configuration,我如何确定子配置元素是否完全缺失,或者仅仅是空的?

测试程序

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MissingConfigElementTest
{
    class MyConfigurationElement : ConfigurationElement
    {
        [ConfigurationProperty("name")]
        public string Name
        {
            get { return (string)base["name"]; }
        }
    }

    class MyConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("empty", DefaultValue = null)]
        public MyConfigurationElement Empty
        {
            get { return (MyConfigurationElement)base["empty"]; }
        }

        [ConfigurationProperty("missing", DefaultValue = null)]
        public MyConfigurationElement Missing
        {
            get { return (MyConfigurationElement)base["missing"]; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var configSection = (MyConfigurationSection)ConfigurationManager.GetSection("mySection");

            Console.WriteLine("Empty.Name: " + (configSection.Empty.Name ?? "<NULL>"));
            Console.WriteLine("Missing.Name: " + (configSection.Missing.Name ?? "<NULL>"));

            Console.ReadLine();
        }
    }
}

测试配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="mySection" type="MissingConfigElementTest.MyConfigurationSection, MissingConfigElementTest"/>
  </configSections>
  <mySection>
    <empty />
  </mySection>
</configuration>

输出

输出是

Empty.Name: 
Missing.Name:

问题

我找不到一种方法来区分空的但存在的配置元素和整个配置元素被遗漏的情况。

我想要这个是因为如果存在一个元素,我想确保它通过特定的验证逻辑,但完全不包含该元素也很好。

最佳答案

此外,ElementInformation.IsPresent属性可用于确定元素是否存在于原始配置中。

var configSection = ( MyConfigurationSection ) ConfigurationManager.GetSection( "mySection" );

Console.WriteLine( "Empty.Name: " + ( configSection.Empty.ElementInformation.IsPresent ? configSection.Empty.Name : "<NULL>" ) );
Console.WriteLine( "Missing.Name: " + ( configSection.Missing.ElementInformation.IsPresent ? configSection.Missing.Name : "<NULL>" ) );

Console.ReadLine( );

这将输出

Empty.Name:
Missing.Name: <NULL>

关于c# - 如何识别缺少的 ConfigurationElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25446364/

相关文章:

c# - 如何从事件目录中获取用户列表?

c# - 为什么 "in"关键字允许 C# 属性发生变化?

java - 如何获取当前的屏幕方向?

error-handling - 在Struts 2中找不到 Action 时如何处理404错误

c# - Xamarin 未处理的异常无法从程序集中加载 MainActivity

php - 在 php.ini 中默认将 FTP 设置为被动模式

c# - 在日期的自定义格式中使用撇号 ' '

c# - 静态与非静态方法

c# - session 在 Controller 方法中变为空

c# - 创建自动打开的文档