在自动启动时将参数传递给Windows服务

时间:2017-03-15 14:15:18

标签: c# windows-services

我发现了一些类似的问题,但答案在我的案例中似乎并没有帮助。我希望使用1个参数配置我的自动启动服务。

我的服务OnStart方法如下所示:

    /// <summary>
    /// Starts the service
    /// </summary>
    /// <param name="args">args must contain the listening port number of the service</param>
    protected override void OnStart(string[] args)
    {
        if (args != null && args.Length > 0)
        {
            int port = -1;
            if (int.TryParse(args[0], out port) && port >= 0 && port <= 65535)
            {
                server.Start(port);
            }
            else
            {
                Log.Entry("Port value " + args[0] + " is not a valid port number!", Log.Level.Error);
            }
        }
        else
        {
            Log.Entry("Service must be started with the port number (integer) as parameter.", Log.Level.Error);
            throw new ArgumentNullException("Service must be started with the port number (integer) as parameter."); // stop the service!
        }
    }

所以我在服务文件名之后用int参数(8081)注册了我的服务,如下面的截图所示(正如其他类似问题的答案所示)。

enter image description here

当我启动服务时,我总是收到错误消息&#34;必须启动服务....&#34;。

如果我在&#34;开始参数中输入一个整数:&#34;服务正常。

如何使用一个参数(8081)让Windows自动启动我的服务?

修改:

  

我做了一些测试。添加了args []参数的日志记录。它是   空。此外,我尝试添加额外的参数,如下图所示:

     

enter image description here

     

我在参数周围使用和不使用双引号都尝试过,但是   他们没有被传递给服务。

2 个答案:

答案 0 :(得分:5)

启动服务时,有两个不同的参数列表。

第一个是从命令行获取的,如服务管理工具中的“可执行文件的路径”所示。这是您将参数8081放在屏幕截图中所示的位置。

在.NET服务中,这些参数将传递给Main()函数。

第二个是服务启动参数,它们是在手动启动服务时提供的。如果使用“服务”管理工具启动服务,则此参数列表将从“开始参数”字段中获取,该字段在屏幕截图中为空。

在.NET服务中,这些参数将传递给OnStart()函数。

因此,在您的方案中,您应该修改Main(),以便将命令行参数传递给您的服务类。通常,您可以在构造函数中提供这些,但如果您愿意,可以使用全局变量。

(有关服务启动的详细说明,另请参阅this answer。)

答案 1 :(得分:2)

@Harry Johnston的回答是正确的。我只是想添加一些代码来支持它。

该服务的入口点位于文件&#34; Program.cs&#34;中。默认情况下,它看起来像这样:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service()
        };
        ServiceBase.Run(ServicesToRun);
    }
}

没有参数传递给服务。添加args参数允许服务接收参数。

static class Program
{
    static void Main(string[] args)
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service(args[0])
        };
        ServiceBase.Run(ServicesToRun);
    }
}

然后,您只需要向接受参数的服务添加构造函数。

现在可以使用参数自动启动服务。

相关问题