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

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>

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


当前回答

我做了我认为很明显的事

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

在编译时,它总是返回null。

然而,这(从上面)是可行的:

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

其他回答

我的简单测试也失败了,遵循这里的其他答案的建议—直到我意识到我添加到桌面应用程序的配置文件的名称为“App1.config”。我将其重命名为“App.config”,一切都立即正常工作。

在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。 最好的问候: 拉斐尔

或者你可以用

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

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

你可以简单地输入:

string filePath = Sysem.Configuration.ConfigurationManager.AppSettings[key.ToString()];

因为key是一个对象,AppSettings接受一个字符串

试试这个:

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