首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.NET Config文件:如何检查是否存在ConfigSection

.NET Config文件:如何检查是否存在ConfigSection
EN

Stack Overflow用户
提问于 2014-05-02 14:47:20
回答 8查看 7K关注 0票数 10

考虑:

这句话:

<section name="unity" />

街区:

代码语言:javascript
复制
<unity>
    <typeAliases />
    <containers />
</unity>

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

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

编辑

对于那些天才的人来说,他们很快就把这个问题标记为否定的:

我已经试过ConfigurationManager.GetSection()

代码语言:javascript
复制
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

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

var sInfo = section.SectionInformation;

var isDeclared = sInfo.IsDeclared;

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

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2015-02-26 20:13:13

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

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

代码语言:javascript
复制
//After Deserialization
if(customSection.ElementInformation.IsPresent == false)
    Console.WriteLine("Section Missing");

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

代码语言:javascript
复制
if(customSection.propName.ElementInformation.IsPresent == false)
    Console.WriteLine("Configuration Element was not found.");

当然,如果要检查是否缺少定义,请使用以下方法:

代码语言:javascript
复制
CustomSection mySection = 
    config.GetSection("MySection") as CustomSection;

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

-Hope,这很有帮助

票数 16
EN

Stack Overflow用户

发布于 2015-08-30 14:43:53

我就是这样解决这个问题的。

代码语言:javascript
复制
var unitySection = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
if (unitySection != null && unitySection.Containers.Count != 0)
    container.LoadConfiguration();

第一个检查用于定义,第二个检查用于块。

票数 2
EN

Stack Overflow用户

发布于 2014-05-02 15:01:40

与其他类似,我认为您需要使用ConfigurationManager.GetSection()。但是,如果我正确地阅读了您的问题,您是否要求检查统一是否存在于name=“统一”一节中?如果是这样的话,您将需要这样做:

代码语言:javascript
复制
ConfigurationManager.GetSection("unity/unity");

然后,如果您想要或做类似于RB建议的事情,您可以检查cs。

*编辑*

好吧,这个怎么样,有点长,但可能有用:

代码语言:javascript
复制
ConfigurationSection section = ConfigurationManager.GetSection("unity");
System.Xml.XmlDocument xmlData = new System.Xml.XmlDocument();
xmlData.LoadXml(section);

XmlNode Found = null;

foreach (System.Xml.XmlNode node in xmlData.ChildNodes)         
{             
    if (node.HasChildNodes) 
    {        
        Found = FindNode(node.ChildNodes, "unity"); 
    }          
}

if(Found == null) //do something   
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23430938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档