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

sac*_*rni 6 c# installer windows-services app-config

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

ConfigurationManager.AppSettings["CONFIG_FILE"]
Run Code Online (Sandbox Code Playgroud)

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

小智 17

尝试:

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


Dav*_*ras 3

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

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

如果您通过 InstallUtil 调用它,那么配置文件将被定义为 InstallUtil.exe.config,这不是您想要的。您可以使用 Configuration 手动加载配置文件,但这可能会有点混乱

诀窍在于安装程序类的执行上下文。如果您使用 InstallUtil 安装应用程序,则所有代码都将在与 InstallUtil.exe 相同的进程中执行。如果您需要在部署期间将一些数据传递给 Installer 类,则应使用安装参数。它们在执行环境(installutil、windows installer...)执行 Install、Commit、Rollback 和 Uninstall 方法期间传递给安装程序。您可以使用安装程序类的 InstallContex 属性访问这些参数。

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

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