【问题标题】:How to determine if a config section or element is loaded from app.config or machine.config?如何确定配置部分或元素是从 app.config 还是 machine.config 加载的?
【发布时间】:2012-05-16 20:38:38
【问题描述】:

我正在像这样从配置中加载绑定部分

var bingingsSection = BindingsSection.GetSection(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));

如何确定加载的配置元素是来自本地应用程序配置文件还是来自 machine.config?

【问题讨论】:

    标签: c# .net c#-4.0 .net-4.0 config


    【解决方案1】:

    使用属性绑定Section.EvaluationContext.IsMachineLevel。

    EvaluationContext.IsMachineLevel 也可用于 ConfigurationElements,这样您就可以为每个单独的配置值确定它。

    【讨论】:

    • 我从 app.config 中注释掉了整个 部分,但 IsMachineLevel 仍然是错误的,还有其他想法吗?
    • 还有 EvaluationContext.HostingContext 属性。您的调试器中的这个属性是什么?
    • @C.Zonnenberg- 它显示了我本地 app.config 和 UserLevel = None 的 exe 路径
    • @C.Zonnenberg- 我找到了一种方法来确定配置元素的来源。看我的回答...
    【解决方案2】:

    我自己找到了正确答案。

    我需要检查ElementInformation.Source 属性。

    给定以下配置:

    <?xml version="1.0"?>
    <configuration>
        <system.serviceModel>
            <bindings>
                <netTcpBinding>
                    <binding maxReceivedMessageSize="1000000"/>
                </netTcpBinding>
            </bindings>
        </system.serviceModel>
        <startup>
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
        </startup>
    </configuration>
    

    还有下面的应用

    using System;
    using System.Configuration;
    using System.ServiceModel.Configuration;
    
    namespace ConsoleApplication49
    {
        class Program
        {
            static void Main(string[] args)
            {
                var config          = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var bingingsSection = BindingsSection.GetSection(config);
    
                string netTcpSource    = bingingsSection.NetTcpBinding.ElementInformation.Source;
                string basicHttpSource = bingingsSection.BasicHttpBinding.ElementInformation.Source;
    
                Console.WriteLine("Net TCP Binding came from \"{0}\"", netTcpSource);
                Console.WriteLine("Basic HTTP Binding came from \"{0}\"", basicHttpSource);
            }
        }
    }
    

    产生输出:

    Net TCP Binding came from "c:\users\Jim\documents\visual studio 2010\Projects\ConsoleApplication49\ConsoleApplication49\bin\Debug\ConsoleApplication49.exe.Config"
    Basic HTTP Binding came from ""
    Press any key to continue . . .
    

    因此,您可以看到在我的本地可执行文件的 app.config 中定义的元素显示了配置路径,但是,我引用的未在本地可执行文件的 app.config 中指定的元素返回了一个空白字符串。大概是因为它是默认的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-18
      • 2013-09-07
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      • 2016-07-09
      相关资源
      最近更新 更多