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?
Startup parameters change the behavior of the Service Manager server. You can always set a startup parameter from the server's operating system command prompt.
Open Start. Search for Command Prompt, right-click the top result, and select the Run as administrator option. Type the following command to enable a service and press Enter: sc config "SERVICE-NAME" start=auto In the command, replace "SERVICE-NAME" for the name of the service that you want to enable.
You can pass parameters on startup like this:
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 }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With