如何在单个项目中从 c# 中的多个配置文件中读取值? [英] How to read values from multiple Configuration file in c# within a single project?

查看:52
本文介绍了如何在单个项目中从 c# 中的多个配置文件中读取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here in my project I have two application configuration files called app.config and accessLevel.config. Now using the OpenExeConfiguration I was able to access the app.config.exe file but not the accessLevel.config. Please help on this.

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

The main reason I have 2 config files is to show the difference and make the code simple. I need to read the values from the accessLevel.config in my C# code.

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

Tried the below code but no use:

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

推荐答案

参见 这里.

把它放在你的 App.config 中:

<appSettings file="accessLevel.config"/>

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

And then have another file called accessLevel.config like this:

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

然后你可以在这样的代码中访问你的配置值:

And then you can access your config values in code like this:

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

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

Make sure that accessLevel.config is set to copy to the output directory (right click the file in Visual Studio -> Properties -> Copy To Output Directory -> Copy if Newer).

这篇关于如何在单个项目中从 c# 中的多个配置文件中读取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆