Windows服务安装程序无法读取App.Config文件

时间:2011-10-03 10:40:38

标签: c# windows-services installer app-config

我在我的项目中添加了App.Config。 我有一个安装程序类(ProjectInstaller.cs),它需要从App.config中读取值。 我提供钥匙。 以下是示例代码:

ConfigurationManager.AppSettings["CONFIG_FILE"]

在Installer类中调用时,我按照上面的代码获取空值。 但是在App.Config文件中,存在上述键的值。

4 个答案:

答案 0 :(得分:16)

尝试:

public string GetServiceNameAppConfig(string serviceName)
{
    var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetAssembly(typeof(MyServiceInstaller)).Location);
    return config.AppSettings.Settings[serviceName].Value;
}

答案 1 :(得分:3)

Google帮助:http://social.msdn.microsoft.com/Forums/ar/winformssetup/thread/896e110e-692d-4934-b120-ecc99b01c562

关键是您的安装程序 NOT 单独作为exe运行,默认情况下,默认情况下不会加载任何您想象的app.config,因为运行安装程序的exe是 InstallUtil.exe ,它最终将从文件 InstallUtil.exe.config 搜索appSettings,这不是你的,不是你想要的,请阅读以下内容并查看链接...

  

如果通过InstallUtil调用它,则配置文件为   定义为InstallUtil.exe.config,这不是你想要的。您   可以使用Configuration手动加载配置文件   可能有点凌乱

     

诀窍在于安装程序类的执行上下文。如果你   使用InstallUtil安装你的应用程序所有代码都将在中执行   与InstallUtil.exe相同的过程。如果你需要传递一些数据   部署期间的安装程序类应该使用安装参数。   它们在执行Install,Commit时传递给安装程序,   执行环境的回滚和卸载方法   (installutil,windows instller ...)。您可以访问那些参数   使用InstallContex属性或安装程序类。

     

CodeProject上有关于安装项目的精彩文章   和参数:   http://www.codeproject.com/dotnet/SetupAndDeployment.asp

     

退房   http://msdn2.microsoft.com/en-us/library/system.configuration.install.installcontext.aspx

答案 2 :(得分:1)

对我来说,最简单的解决方案是创建InstallUtil.exe.config文件,并用应用程序配置文件中的内容填充它。服务安装程序已成功从此配置文件中读取。

我按照以下步骤创建了我的服务:Host a WCF Service in a Managed Windows Service

答案 3 :(得分:1)

Davide Piras解释得非常好,为什么你不能使用你的app.config并建议将你的值作为参数传递。

我找到了一篇很好且有帮助的文章,介绍了如何将参数传递给installutil.exe并在serviceInstallerprojectInstaller中使用它们:

第1部分:Using Parameters with InstallUtil

第2部分:Configuring Windows Services with Parameters from InstallUtil

它很快解释了如何传递参数以及如何阅读它们。