我想在安装之前为 Windows 服务设置用户帐户。 我通过在项目安装程序中添加代码来实现。
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User; this.serviceProcessInstaller1.Password = ConfigurationSettings.AppSettings["密码"]; this.serviceProcessInstaller1.Username = ConfigurationSettings.AppSettings["用户名"];
仍然提示输入用户名和密码。看起来在安装完成时配置文件还没有准备好。
我怎样才能从配置文件中提取用户名和密码而不是对其进行硬编码?
最佳答案
嗯,我不知道为什么 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;
关于Windows 服务设置用户帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3474198/