【问题标题】:How to read configuration from a config file into the strong-typed Settings object如何将配置文件中的配置读入强类型设置对象
【发布时间】:2013-11-08 18:02:54
【问题描述】:

上下文:我正在开发一个供同事使用的库(我们称之为InternalLib),但从他们的角度来看,它是一个外部程序集。在InternalLib中,我也需要使用一个外部库(我们称之为ExternalLib),我使用ILMerge将它合并到InternalLib中。

InternalLibExternalLib 都需要使用 app.config 中的配置。我知道我的同事可以在他们的 app.config 中为 InternalLibExternalLib 定义 configSections 并链接 applicationSettings,但是 有没有办法我可以读取配置来自不同的配置文件?(例如,InternalLib.dll.config)我宁愿给他们一个 dll 和一个 .config,而不是要求他们将 n 配置部分添加到他们的配置文件。

我可以更改 InternalLib 以使用 ExeConfigurationFileMap 将配置文件读入 Configuration 对象,但我无法控制 ExternalLib 从何处获取配置文件。我的意思是,即使我将 ExternalLib 的配置放入 Configuration 对象中,我也无法告诉 ExternalLib 使用该对象而不是 @987654327 @,可以吗?

【问题讨论】:

标签: c# app-config .net-4.5 configuration-files


【解决方案1】:

您可以通过以下方式更改项目使用的配置文件:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", AppDomain.CurrentDomain.BaseDirectory + confFolder + "app.config");

如果需要,之后可以重置

    private void ResetConfigMechanism()
    {
        typeof(ConfigurationManager)
            .GetField("s_initState", BindingFlags.NonPublic |
                                     BindingFlags.Static)
            .SetValue(null, 0);

        typeof(ConfigurationManager)
            .GetField("s_configSystem", BindingFlags.NonPublic |
                                        BindingFlags.Static)
            .SetValue(null, null);

        typeof(ConfigurationManager)
            .Assembly.GetTypes()
            .Where(x => x.FullName ==
                        "System.Configuration.ClientConfigPaths")
            .First()
            .GetField("s_current", BindingFlags.NonPublic |
                                   BindingFlags.Static)
            .SetValue(null, null);
    }

Further reading

【讨论】:

  • 这真的很有趣,除了一个小问题之外,它实际上做了我想要的。如您所知,它会重置整个应用程序的配置。我将研究“保存旧配置并在之后重新加载”,但如果调用应用程序修改了某些设置并且尚未保存它们,我担心它会导致不良影响。调查一下。
  • 我还没有找到一种干净的方法来临时保存对配置的挂起更改、加载我的配置、使用它并恢复临时状态,但是因为应用程序更改设置是非常不寻常的,并且在那一刻不保存它们,我将在我的用户文档中添加一个关于它的注释并以这种方式进行。谢谢山姆。
【解决方案2】:

您可以使用 XmlSerializer,例如(简化,无错误处理等):

public class Config<T> where T : class
{
    public static T Load()
    {
        using (var reader = new StreamReader("config.xml"))
        {
            return (T)(new XmlSerializer(typeof(T))).Deserialize(reader);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-16
    • 2014-04-21
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多