c# - 如何在用 C# 编写的 Windows 服务中获取 ServiceName?

标签 c# .net windows-services

如何在用 C# 编写的 Windows 服务中使用 this.ServiceName 以编程方式获取服务名称?当我尝试这样做时,它要求提供程序集引用但不接受任何内容:

string path = this.ServiceName + ".config";

但出现错误。

最佳答案

您的服务需要从 System.ServiceProcess.dll 继承 ServiceBase

当您拥有它时,您将能够访问 this.ServiceName 属性。

示例:

public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        string test = this.ServiceName;
    }

    protected override void OnStop()
    {
    }
}

如果你想从 Main()(程序类)访问它,那么你可以这样做:

namespace WindowsService1
{
    static class Program
    {
        static ServiceBase[] _servicesToRun;

        static void Main()
        {
            _servicesToRun = new ServiceBase[] 
            { 
                new Service1() 
            };

            string serviceName = _servicesToRun[0].ServiceName;

            ServiceBase.Run(_servicesToRun);
        }
    }
}

关于c# - 如何在用 C# 编写的 Windows 服务中获取 ServiceName?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4657355/

相关文章:

c# - 用于验证 double 值的正则表达式

c# - 在 Windows 窗体中为控件使用通用事件处理程序!

c# - 将字节 * 传递给 Stream.Read(byte[], int, int)

c# - 如何优化分配的真实状态

c# - 一个 map 网络如何从windows服务驱动?

c# - STAThread 属性是要求还是建议?

c# - 如何使用 Expression.Add 对 double 和 int 求和?

c# - TimeZoneInfo - .net core 1.1 上的调整规则错误

c# - 我可以在没有定时器组件的情况下使用定时器吗?

windows-services - 将 Growl 作为 Windows 服务运行