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