22

I tried to pass parameters to a windows service.

Here is my code snippet:

class Program : ServiceBase
{
    public String UserName { get; set; }
    public String Password { get; set; }

    static void Main(string[] args)
    {
        ServiceBase.Run(new Program());
    }

    public Program()
    {
        this.ServiceName = "Create Users Service";
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);

        String User = UserName;
        String Pass = Password;
        try
        {
            DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");

            DirectoryEntry NewUser = AD.Children.Add(User, "user");
            NewUser.Invoke("SetPassword", new object[] { Pass });
            NewUser.Invoke("Put", new object[] { "Description", "Test User from .NET" });
            NewUser.CommitChanges();
            DirectoryEntry grp;
            grp = AD.Children.Find("Administrators", "group");
            if (grp != null)
            {
                grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
            }
            Console.WriteLine("Account Created Successfully");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.ReadLine();
        } 
    }

How do I pass UserName and Password to this windows service?

1
  • How to pass UserName and Password to this windows service? Commented Jun 27, 2011 at 9:35

7 Answers 7

33

You can pass parameters on startup like this:

  1. Right click on MyComputer and select Manage -> Services and Applications -> Services
  2. Right click on your service, select Properties and you should then see the Start Parameters box under the General tab.

If you enter there for example User Password you will get these parameters in protected override void OnStart(string[] args) as args. then use it like this:

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    UserName = args[0];
    Password = args[1];
    //do everything else
}
3
  • 8
    as of win7 (at least) this only works to set the parameters to use when starting the service from the Properties dialog box Commented Nov 20, 2013 at 21:05
  • @MartinSerrano Hi. Sorry didn't understood what you mean
    – Renatas M.
    Commented Nov 21, 2013 at 7:33
  • the dialog only lets you set those parameters for starting the service once. to make it permanent you have to do something like in the 2nd answer here: stackoverflow.com/questions/2243753/… Commented Nov 24, 2013 at 0:42
6

You are going to have to load these values up from an external source. The easiest is to load them directly from an app.config file, using the Configuration Manager. Something like this: http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx

3

You can use configuration file, Registry or any type of databases.

0
1

Use Environment.GetCommandLineArgs()

1

You can pass parameters to windows service when starting it. Run cmd with administrator privileges and enter following command:

sc start <ServiceName> param1 param2

And if you want to use it one time forever you can store parameters into a file or app.config.

0

The two cleanest ways to pass arguments (without using registry, files or a database) to a Windows Service at runtime is using Named Pipes or setting up a WCF Service in windows, that your client calls into. By default, a Windows Service is meant to be a repetitive process that runs.

If you use WCF, turn it on in Add Remove Programs (or Programs and Features for Windows 7).

Named Pipes:

https://msdn.microsoft.com/en-us/library/aa365590(v=vs.85).aspx

0

I struggled with the same issue except I was installing the service within a program. I'm using sc.exe to install the service and the secret was to pass the application path and its command line arguments to sc.exe within double quotes:

From the command line:

sc create myservice "myservice.exe -fappsettings.json"  

In code:

using (var process = new Process())
{
  process.StartInfo.FileName = "sc.exe";
  process.StartInfo.Arguments = $"create {serviceName} start= auto error= normal binpath= \"{Environment.ProcessPath} -fappsettings.ini\" displayname= {displayName}";
  process.StartInfo.Verb = "runas";
  process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
  process.Start();
  process.WaitForExit();
}

For the OP, passing usernames and passwords en clear on the command line in the context of a service is a security risk. Put them in a settings file as someone else mentioned and use the above to specify the settings. Remember that the services control manager will have the current working directory set to c:\windows\services32 or similar.

A

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.