How to pass parameters to Windows Service?

前端 未结 6 2467
猫巷女王i
猫巷女王i 2020-12-16 11:21

I tried to pass parameters to a windows service.

Here is my code snippet:

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


        
相关标签:
6条回答
  • 2020-12-16 12:13

    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

    0 讨论(0)
  • 2020-12-16 12:17

    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 讨论(0)
  • 2020-12-16 12:23

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

    0 讨论(0)
  • 2020-12-16 12:26

    Use Environment.GetCommandLineArgs()

    0 讨论(0)
  • 2020-12-16 12:26

    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 讨论(0)
  • 2020-12-16 12:27

    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
    }
    
    0 讨论(0)
提交回复
热议问题