考虑:
这句话:
<section name="unity" />
街区:
<unity>
<typeAliases />
<containers />
</unity>假设该行在.config文件中可用,而该块丢失。
如何以编程方式检查该块是否存在?
编辑
对于那些天才的人来说,他们很快就把这个问题标记为否定的:
我已经试过ConfigurationManager.GetSection()了
和
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var section = config.GetSection("unity");
var sInfo = section.SectionInformation;
var isDeclared = sInfo.IsDeclared;如果我弄错了,请纠正我,如果定义了<configSections>,上面不会返回null (即使缺少实际的统一块)。
发布于 2015-02-26 20:13:13
由于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.");-Hope,这很有帮助
发布于 2015-08-30 14:43:53
我就是这样解决这个问题的。
var unitySection = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
if (unitySection != null && unitySection.Containers.Count != 0)
container.LoadConfiguration();第一个检查用于定义,第二个检查用于块。
发布于 2014-05-02 15:01:40
与其他类似,我认为您需要使用ConfigurationManager.GetSection()。但是,如果我正确地阅读了您的问题,您是否要求检查统一是否存在于name=“统一”一节中?如果是这样的话,您将需要这样做:
ConfigurationManager.GetSection("unity/unity");然后,如果您想要或做类似于RB建议的事情,您可以检查cs。
*编辑*
好吧,这个怎么样,有点长,但可能有用:
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 https://stackoverflow.com/questions/23430938
复制相似问题