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

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>

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


当前回答

在很长一段时间后回到这个话题…

鉴于ConfigurationManager的消亡,对于仍然在寻找这个尝试的答案的人(例如):

AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));

需要系统。当然是构型。

(将代码编辑为实际工作并且更易于阅读的内容)

其他回答

我正在使用:

    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

dtsg给出的答案是:

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

但是,您需要添加程序集引用

系统。配置

转到解决方案资源管理器,右键单击“引用”并选择“添加引用”。选择“程序集”选项卡并搜索“配置”。

这是我的App.config的一个例子:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="AdminName" value="My Name"/>
    <add key="AdminEMail" value="MyEMailAddress"/>
  </appSettings>
</configuration>

你可以通过以下方式获得:

string adminName = ConfigurationManager.AppSettings["AdminName"];

这对我来说很管用:

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

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

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

以下是我对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;