如何在单个项目中从c#中的多个配置文件中读取值?

Pra*_*een 9 c# configurationmanager app-config config configuration-files

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

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

尝试以下代码但没有用:

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.File = "App2.config";
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 25

看到这里.

把它放在你的App.config:

<appSettings file="accessLevel.config"/>
Run Code Online (Sandbox Code Playgroud)

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

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
  <add key="TestSetting" value="TestValue"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)

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

string value = ConfigurationManager.AppSettings["TestSetting"];
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意,第二个配置(_accessLevel.config_)以`<appSettings />`元素开头,而不是默认的`<configuration />`元素.在我意识到这一点之前,我花了大约10分钟;) (3认同)