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

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

. config文件:

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

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


当前回答

在app/web中。配置文件设置如下配置:

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

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

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

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

其他回答

ConfigurationManager.RefreshSection("appSettings")
string value = System.Configuration.ConfigurationManager.AppSettings[key];

以下是我对2016年的看法

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

确保系统。引用配置。

问题是询问appsettings键的值

哪个才是最应该的呢

  string yourKeyValue = ConfigurationManager.AppSettings["ClientsFilePath"]

  //yourKeyValue should hold on the HEAP  "filepath"

这里有一个可以将值组合在一起的方法(不是针对这个问题)

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

电子邮件将是环境键+ " _email "的值

example :   jack@google.com;thad@google.com;

在我的情况下,我必须在@System.Configuration.ConfigurationManager的两侧抛出一个“on either side”。AppSettings["key"]'以便它作为字符串读入我的程序。我使用Javascript,所以这是在我的标签。注意:ToString()不适合我。

试试这个:

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

或者你可以用

string value = system.configuration.ConfigurationManager.AppSettings.Get("ClientsFilePath");

//Gets the values associated with the specified key from the System.Collections.Specialized.NameValueCollection