设置服务的运行凭据

kma*_*ks2 7 .net c# windows service windows-services

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

在下面的示例中serviceUser,servicePassword它们只是对象范围的私有字符串.

以下块(驻留在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
}
Run Code Online (Sandbox Code Playgroud)

但是,以下不起作用:

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*
}
Run Code Online (Sandbox Code Playgroud)

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

为什么这会失败?

编辑:通过"失败"我的意思是服务安装程序提示输入密码,无论用户放置什么覆盖serviceUserservicePassword.