如何确定配置部分或元素是从 app.config 还是从 machine.config 加载的

本文关键字:config machine 加载 何确定 app 元素 配置部 | 更新日期: 2023-09-27 18:34:28

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

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

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

如何确定配置部分或元素是从 app.config 还是从 machine.config 加载的

使用属性 bindingsSection.EvaluationContext.IsMachineLevel。

EvaluationContext.IsMachineLevel 也可用于 ConfigurationElements,因此您可以为每个配置值确定它。

我自己找到了正确的答案。

我需要检查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 中指定的元素返回了一个空白字符串。大概是因为它是默认值。