C# AppSettings 从 .config 文件中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10766654/
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-09 15:10:12  来源:igfitidea点击:

AppSettings get value from .config file

c#.netappsettingsconfigurationmanager

提问by Matt

I'm not able to access values in configuration file.

我无法访问配置文件中的值。

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var clientsFilePath = config.AppSettings.Settings["ClientsFilePath"].Value; 
// the second line gets a NullReferenceException

.config file:

.config 文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!-- ... -->
    <add key="ClientsFilePath" value="filepath"/>
    <!-- ... -->
  </appSettings>
</configuration>

Do you have any suggestion what should I do?

你有什么建议我该怎么做?

采纳答案by Adam

This works for me:

这对我有用:

string value = System.Configuration.ConfigurationManager.AppSettings[key];

回答by dtsg

Give this a go:

试一试:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

回答by Kkloe

I am using:

我在用:

    ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
    //configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
    configMap.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + ServiceConstants.FILE_SETTING;
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
    value1 = System.Configuration.ConfigurationManager.AppSettings["NewKey0"];
    value2 = config.AppSettings.Settings["NewKey0"].Value;
    value3 = ConfigurationManager.AppSettings["NewKey0"];

Where value1 = ...and value3 = ...gives null and value2 = ...works

其中value1 = ...value3 = ...给出 null 和value2 = ...有效

Then I decided to replace the internal app.config with:

然后我决定将内部 app.config 替换为:

// Note works in service but not in wpf
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"d:\test\justAConfigFile.config.whateverYouLikeExtension");
ConfigurationManager.RefreshSection("appSettings");

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

Using VS2012 .net 4

使用 VS2012 .net 4

回答by BCA

My simple test also failed, following the advice of the other answers here--until I realized that the config file that I added to my desktop application was given the name "App1.config". I renamed it to "App.config" and everything immediately worked as it ought.

按照此处其他答案的建议,我的简单测试也失败了——直到我意识到我添加到桌面应用程序的配置文件被命名为“App1.config”。我将它重命名为“App.config”,一切立即正常运行。

回答by rotgers

The answer that dtsg gave works:

dtsg 给出的答案有效:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

BUT, you need to add an assembly referenceto

但你需要添加一个程序集引用

System.Configuration

系统配置

Go to your Solution Explorerand right clickon References and select Add reference. Select the Assembliestab and search for Configuration.

转到您的解决方案资源管理器右键单击References 并选择Add reference。选择组件选项卡并搜索配置

Reference manager

参考经理

Here is an example of my App.config:

这是我的App.config的示例:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="AdminName" value="My Name"/>
    <add key="AdminEMail" value="MyEMailAddress"/>
  </appSettings>
</configuration>

Which you can get in the following way:

您可以通过以下方式获得:

string adminName = ConfigurationManager.AppSettings["AdminName"];

回答by Steve

See I did what I thought was the obvious thing was:

看我做了我认为很明显的事情:

string filePath = ConfigurationManager.AppSettings.GetValues("ClientsFilePath").ToString();

While that compiles it always returns null.

虽然编译它总是返回null。

This however (from above) works:

然而,这(从上面)有效:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

回答by Tom Stickel

Some of the Answers seems a little bit off IMOHere is my take circa 2016

一些答案似乎有点偏离IMO这是我在 2016 年左右的看法

<add key="ClientsFilePath" value="filepath"/>

Make sure System.Configurationis referenced.

确保System.Configuration被引用。

Question is asking for valueof an appsettings key

问题是要求appsettings键的

Which most certainly SHOULD be

最肯定应该是

  string yourKeyValue = ConfigurationManager.AppSettings["ClientsFilePath"]

  //yourKeyValue should hold on the HEAP  "filepath"

Here is a twist in which you can group together values ( not for this question)

这是一个转折,您可以将值组合在一起(不适用于此问题)

var emails = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["Environment"] + "_Emails"];

emailswill be value of Environment Key + "_Emails"

emails将是 Environment Key + "_Emails" 的值

example :   [email protected];[email protected];

回答by Masoud Siahkali

Read From Config :

从配置读取:

You'll need to add a reference to Config

您需要添加对 Config 的引用

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"
  4. Get Value with using following code :
  1. 在您的项目中打开“属性”
  2. 转到“设置”选项卡
  3. 添加“名称”和“值”
  4. 使用以下代码获取价值:
string value = Properties.Settings.Default.keyname;

Save to Config :

保存到配置:

Properties.Settings.Default.keyName = value;
Properties.Settings.Default.Save();

回答by Rafael Andrs Cspedes Basterio

In the app/web.configfile set the following configuration:

app/web.config文件中设置以下配置:

<configuration>
  <appSettings>
    <add key="NameForTheKey" value="ValueForThisKey" />
    ... 
    ...    
  </appSettings>
...
...
</configuration>

then you can access this in your code by putting in this line:

然后你可以通过在你的代码中加入这一行来访问它:

string myVar = System.Configuration.ConfigurationManager.AppSettings["NameForTheKey"];

*Note that this work fine for .net4.5.xand .net4.6.x; but do not work for .net core. Best regards: Rafael

*请注意,这适用于.net4.5.x.net4.6.x;但不工作.net core。最好的问候:拉斐尔

回答by suulisin

For web application, i normally will write this method and just call it with the key.

对于 Web 应用程序,我通常会编写此方法并使用密钥调用它。

private String GetConfigValue(String key)
    {
       return System.Web.Configuration.WebConfigurationManager.AppSettings[key].ToString();
    }