小编McP*_*olu的帖子

如何读取任意.config文件而不是app.config

可能重复:
使用ConfigurationManager从任意位置加载配置

我花了几个小时的时间偷偷看看C#框架类来解决这个问题.关于如何做到这一点有几个问题,但没有明确的答案.我能找到的最好的链接是C#DLL配置文件,它完全涵盖了我的用例,从全局.config文件读取.dll,无论哪个进程托管它.

您可以使用反射来创建处理程序对象,但它会降低可读性,这不是生产代码,只是一个片段来显示它的工作原理.我保持尽可能简单明了.

public class ConfigurationManager
{
    public static object GetSection(string sectionName)
    {
        var configuration =  System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(
                             new System.Configuration.ConfigurationFileMap(
                             @"X:\path\to\your\file.config"));

        object retVal;

        var section = configuration.GetSection(sectionName);
        var xmlDoc = new System.Xml.XmlDocument();
        xmlDoc.LoadXml(section.SectionInformation.GetRawXml());

        if (section.SectionInformation.Type.Equals("System.Configuration.NameValueSectionHandler"))
        {
            var handler = new System.Configuration.NameValueSectionHandler();
            retVal = handler.Create(null, null, xmlDoc.DocumentElement);
        }
        else if (section.SectionInformation.Type.Equals("System.Configuration.DictionarySectionHandler"))
        {
            var handler = new System.Configuration.DictionarySectionHandler();
            retVal = handler.Create(null, null, xmlDoc.DocumentElement);
        }
        else
        {
            throw new System.Exception("Unknown type " + section.SectionInformation.Type);
        }

        return retVal;
    }
}
Run Code Online (Sandbox Code Playgroud)

c# app-config

5
推荐指数
0
解决办法
3253
查看次数

标签 统计

app-config ×1

c# ×1