设置服务的运行凭据

时间:2012-07-03 15:23:12

标签: c# .net windows service windows-services

我有一个服务,其中包含在安装期间使用的app.config文件。在ProjectInstaller类中,有代码来读取app.config文件,提取凭据并设置它们。目标是显示用户/密码提示。

在下面的示例中,serviceUserservicePassword只是对象范围的私有字符串。

以下块(驻留在ProjectInstaller ctor中)可以正常工作。也就是说,它设置服务的登录详细信息,从不提示用户:

public ProjectInstaller()
{
   InitializeComponent();
   LoadServiceSettings();

   //Install the service as a specific user:
   serviceProcessInstaller1.Account = ServiceAccount.User;
   serviceProcessInstaller1.Username = "MYDOMAIN\\myUser";
   serviceProcessInstaller1.Password = servicePassword; //pulled out of app.config by LoadServiceSettings call
}

但是,以下情况不起作用:

public ProjectInstaller()
{
   InitializeComponent();
   LoadServiceSettings();

   //Install the service as a specific user:
   serviceProcessInstaller1.Account = ServiceAccount.User;
   serviceProcessInstaller1.Username = serviceUser; //both get pulled out of app.config by LoadServiceSettings() call;
   serviceProcessInstaller1.Password = servicePassword;

   WriteLog("The service user is *" + serviceUser + "*");
   // The above line outputs:
   // The service user is *MYDOMAIN\myUser*

   WriteLog("Are the strings the same? " + (serviceUser == "MYDOMAIN\\myUser").ToString());
   // The above line outputs:
   // Are the strings the same? True

   WriteLog("Values: *" + serviceUser + "*" + servicePassword + "*");
   // The above line outputs:
   // Values: *MYDOMAIN\myUser*myPassword*

   WriteLog("Values: *" + serviceProcessInstaller1.Username + "*" + serviceProcessInstaller1.Password + "*");
   // The above line outputs:
   // Values: *MYDOMAIN\myUser*myPassword*
}

为什么字符串是否是硬编码的?另外值得注意的是,在我的app.config中我没有逃避斜线...因为它不是一个xml转义字符。

为什么会失败?

编辑:“失败”是指服务安装程序提示输入密码,以及用户放置的任何内容覆盖serviceUserservicePassword

0 个答案:

没有答案