gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:10:43 24 4
gpt4 key购买 nike

如何在用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com