【问题标题】:How to read values from multiple Configuration file in c# within a single project?如何在单个项目中从 C# 中的多个配置文件中读取值?
【发布时间】:2012-09-27 23:23:30
【问题描述】:

在我的项目中,我有两个名为app.configaccessLevel.config 的应用程序配置文件。现在使用OpenExeConfiguration,我可以访问app.config.exe file,但不能访问accessLevel.config。请帮忙。

我有 2 个配置文件的主要原因是为了显示差异并简化代码。 我需要在我的C# 代码中读取accessLevel.config 的值。

尝试了以下代码但没有用:

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.File = "App2.config";

【问题讨论】:

    标签: c# app-config configuration-files config configurationmanager


    【解决方案1】:

    here

    把这个放在你的App.config:

    <appSettings file="accessLevel.config"/>
    

    然后有另一个名为 accessLevel.config 的文件,如下所示:

    <?xml version="1.0" encoding="utf-8" ?>
    <appSettings>
      <add key="TestSetting" value="TestValue"/>
    </appSettings>
    

    然后您可以使用如下代码访问您的配置值:

    string value = ConfigurationManager.AppSettings["TestSetting"];
    

    确保 accessLevel.config 设置为复制到输出目录(在 Visual Studio 中右键单击文件 -> 属性 -> 复制到输出目录 -> 如果较新则复制)。

    【讨论】:

    • 我应该在app.config.exe 中有这行吗?
    • 已经编辑和修复 - 看看你能不能让它工作?您尝试移动到另一个文件或其他配置部分的 appSettings 是什么?无论哪种方式,都适用相同的原则。
    • @Aniket 完成。抱歉,我错过了在正确的时间挑选它。
    • 请注意,第二个配置 (accessLevel.config) 以 &lt;appSettings /&gt; 元素开头,而不是默认的 &lt;configuration /&gt; 元素。我花了大约 10 分钟才意识到这一点;)
    • 这是如何“从多个配置文件中读取值”?通过 app.config 仅读取 accessLevel.config 中的值...
    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多