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

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 value = system.configuration.ConfigurationManager.AppSettings.Get("ClientsFilePath");

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

其他回答

这对我来说很管用:

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

或者你可以用

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

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

你可以这样做:

string value1 = System.Configuration.ConfigurationManager.AppSettings.Get(0); //for the first key


string value2 = System.Configuration.ConfigurationManager.AppSettings.Get(1); //for the first key

试试这个:

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

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