Windows服务设置用户帐户

我想在安装之前设置
Windows服务的用户帐户.

我是通过在项目安装程序中添加代码来实现的.

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User;
this.serviceProcessInstaller1.Password = ConfigurationSettings.AppSettings [“password”];
this.serviceProcessInstaller1.Username = ConfigurationSettings.AppSettings [“username”];

仍然提示输入用户名和密码.看起来配置文件在安装完成之前还没有准备好.

我如何从配置文件中提取用户名和密码而不是硬编码?

最佳答案 好吧,我不知道为什么在安装程序运行时AppSettings值无法以传统方式读取.我自己尝试了,遇到了你遇到的同样的问题.但是,我能够通过将配置文件作为常规XML文件加载并以这种方式读取来解决问题.试试这个:

XmlDocument doc = new XmlDocument();
doc.Load(Assembly.GetExecutingAssembly().Location + ".config");

XmlElement appSettings = (XmlElement)doc.DocumentElement.GetElementsByTagName("appSettings")[0];

string username = null;
string password = null;

foreach (XmlElement setting in appSettings.GetElementsByTagName("add"))
{
    string key = setting.GetAttribute("key");
    if (key == "username") username = setting.GetAttribute("value");
    if (key == "password") password = setting.GetAttribute("value");
}

serviceProcessInstaller1.Account = ServiceAccount.User;
serviceProcessInstaller1.Username = username;
serviceProcessInstaller1.Password = password;
点赞