ConfigurationManager.AppSettings使用另一个配置文件

本文关键字:另一个 配置文件 AppSettings ConfigurationManager | 更新日期: 2023-09-27 18:12:44

我的类中大约有10个方法。在每种方法中,我使用ConfigurationManager.AppSettings从App.config文件

获取值

 _applicationPort = int.Parse(ConfigurationManager.AppSettings["ApplicationPort"]

我的问题是,我想让这段代码获得AppSettings从另一个app.config文件,如anotherproject .exe.config.

ConfigurationManager.AppSettings使用另一个配置文件

您也可以设置app.config读取其他文件。像这样:

<?xml version="1.0"?>
<configuration>
  <appSettings  file="my'custom'file'path'external.config"/>
</configuration>

external.config将有appSettings部分:

<appSettings>
    <add key="myKey" value="myValue" />
</appSettings>

你可以这样做

var fileConfig = ConfigurationManager.OpenExeConfiguration("<filePath>");
int port = int.Parse(fileConfig.AppSettings["PortNumber"].ToString());

您可以使用ConfigurationManager.OpenExeConfiguration来完成此操作。这将允许您轻松打开另一个配置文件。

关于openexecconfiguration的MSDN文章。