windows 服务无法读取 app.config C#

windows service cannot read app.config C#

我创建了一个 windows 服务,并且有一个 app.config 与之配套。使用 InstallUtil 实用程序后,我的服务已安装,并且在服务目录中它已将 app.config 文件正确转换为 servicename.config 文件。当我检查文件时,AppSettings 具有我期望的所有键。在我的代码中,基本上在 OnStart 事件中有以下行:

string timeToRun = ConfigurationManager.AppSettings["RunTime"];

在 windows 事件查看器中它告诉我由于 System.Configuration.ConfigurationErrorsException

抛出了异常

我不知道为什么我们有其他 windows 服务使用配置文件中的 appSetings 以与上述相同的方式工作。对于此应用程序,执行以下操作似乎可以解决问题:

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection appSettings = configuration.AppSettings;    
string timeToRun = appSettings.Settings["RunTime"].Value;