views:

27

answers:

1

Hi I want to set the user account for Windows Service even before installing. I am doing it by adding code in project installer.

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

Still its prompting for Username and password. Looks like the configuration file is not getting ready by the time the installation is done.

How I can i pull the username and password from configuration file instead of hardcoding it?

A: 

Well, I'm at a loss to say why the AppSettings values are not readable in the traditional manner while the installer is running. I tried it myself and ran into the same problem you are having. However, I was able to get around the problem by loading the configuration file as a regular XML file and reading it that way. Try this:

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;
Brian
Thanks for the solution. It worked. But i have one doubt. If I need to change the username, I anyway need to change the config file and build it again to make the installer. How is this feature going to help me?
Ramyacurious
You should not need to rebuild the project; that is the point of using a config file. You can simply update the config file and then reinstall the service. As for how this feature will help you, I was assuming you already had a good reason for needing to get the values from a config file during installation, otherwise you would have asked a different question! This solution will not allow you to dynamically change the account that the service is running under once it has been installed, if that is what you are trying to do. That is a different problem.
Brian