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

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>

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


当前回答

阅读配置:

您需要添加一个对Config的引用

打开项目上的“属性” 进入“设置”选项卡 添加“名称”和“值” 使用以下代码获取价值:

string value = Properties.Settings.Default.keyname;

保存到配置:

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

其他回答

或者你可以用

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

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

对于web应用程序,我通常会写这个方法,只是用键调用它。

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

我做了我认为很明显的事

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

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

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

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

试试这个:

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