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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16425407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:58:59  来源:igfitidea点击:

ConfigurationManager.AppSettings use another config file

c#configurationapp-config

提问by Tarek Saied

I have about 10 methods in my class. In every method I use ConfigurationManager.AppSettingsto get value form App.config file

我的班级大约有 10 种方法。在我ConfigurationManager.AppSettings用来从 App.config 文件中获取价值的每种方法中

like

喜欢

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

My problem is that I want to make this code get AppSettings from another app.config file like AnotherPoject.exe.config.

我的问题是我想让这段代码从另一个 app.config 文件(如 AnotherPoject.exe.config)中获取 AppSettings。

回答by Justin

You can accomplish this by using ConfigurationManager.OpenExeConfiguration. This will allow you to open another configuration file easily.

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

MSDNarticle about OpenExeConfiguration.

关于 OpenExeConfiguration 的MSDN文章。

回答by Bearcat9425

You could do something like this

你可以做这样的事情

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

回答by Tobia Zambon

You can also set the app.configto read another file. Something like this:

您还可以设置app.config读取另一个文件。像这样的东西:

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

and the external.configwill have the appSettings section:

并且external.config将有 appSettings 部分:

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

refer to this msdnfor additional info.

有关其他信息,请参阅此 msdn