Windows服务无法从我的Installer构造函数中访问app.config

我想将我的Windows服务’登录的用户名/密码信息存储为app.config中的’用户。

所以在我的安装程序中,我试图从app.config中获取用户名/密码并设置属性,但是在尝试安装服务时遇到错误。

如果我硬编码用户名/密码,它工作正常,当我尝试访问app.config时失败

public class Blah : Installer { public Blah() { ServiceProcessInstaller oServiceProcessInstaller = new ServiceProcessInstaller(); ServiceInstaller oServiceInstaller = new ServiceInstaller(); oServiceProcessInstaller.Account = ServiceAccount.User; oServiceProcessInstaller.Username = ConfigurationManager.AppSettings["ServiceProcessUsername"].ToString(); } } 

问题是,当您的安装程序运行时,您仍处于安装阶段,并且您的应用程序尚未完全安装。 app.config仅在运行实际应用程序时可用。

但是,您可以执行以下操作:

  1. 在安装程序(或命令行)中提示用户输入用户名和密码。
  2. 将此信息传递给您的安装程序类(谷歌)
  3. 在安装程序类中,有一个变量可以告诉您安装路径
  4. 在安装程序中的相应事件中,使用System.IO函数打开app.config文件并插入用户输入的信息

关于访问安装程序中的配置文件的一些想法。

 Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyPath); ConnectionStringsSection csSection = config.ConnectionStrings; 

Assembly Path可以通过以下几种方式获得:内部Installer类实现:

 this.Context.Parameters["assemblypath"].ToString(); 

或有时反思:

 Assembly service = Assembly.GetAssembly(typeof(MyInstaller)); string assemblyPath = service.Location; 

我遇到了与服务安装程序相同的问题。 您必须调用配置文件“myService.exe.config”并使用OpenExeConfiguration方法和程序集路径来查找正确的配置文件(正如第一个答案中所述,当您的安装程序运行时,基本目录是installUtil的目录而不是您的安装程序)

 { Assembly __ServiceAssembly = Assembly.GetAssembly(typeof(MyServiceInstaller)); Configuration config = ConfigurationManager.OpenExeConfiguration(__ServiceAssembly.Location); KeyValueConfigurationCollection svcSettings = config.AppSettings.Settings; info("Service name : " + svcSettings["ServiceName"].Value); } 

如果您不想遵循“myService.exe.config”格式,请使用exeConfigurationFileMap:

 { Assembly __ServiceAssembly = Assembly.GetAssembly(typeof(SyslogServiceInstaller)); ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap(); configFileMap.ExeConfigFilename = Path.Combine(Directory.GetParent(__ServiceAssembly.Location).ToString(), "App.config"); Configuration config = ConfigurationManager.OpenMappedExeConfiguration( configFileMap, ConfigurationUserLevel.None); KeyValueConfigurationCollection mySettings = config.AppSettings.Settings; Console.Out.WriteLine(mySettings["ServiceName"].Value); } 

你真的不应该在app.config文件中存储密码,这是非常糟糕的。 您需要使用服务帐户,当前用户或提示他们。 此外,用户可以右键单击.exe(可能是触发您的安装)并选择“运行方式”以在安装之前更改其凭据(在这种情况下,当前用户将是一个很好的选择)。

此外,在服务管理器中,用户可以在安装结束后更改服务应该运行的用户。 但您绝对不希望将密码存储在纯文本文件中。