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

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>

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


当前回答

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

其他回答

或者你可以用

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

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

试试这个:

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

这对我来说很管用:

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

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

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

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

需要系统。当然是构型。

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

阅读配置:

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

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

string value = Properties.Settings.Default.keyname;

保存到配置:

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