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

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>

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


当前回答

我正在使用:

    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"];

其中value1 =…和value3 =…给出null和value2 =…作品

然后我决定用以下内容替换内部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"];

使用VS2012 .net

其他回答

你可以简单地输入:

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

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

这对我来说很管用:

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

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

阅读配置:

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

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

string value = Properties.Settings.Default.keyname;

保存到配置:

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

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

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