[英]How can I get the ServiceName in a Windows Service written in C#?
How can I get the service name programatically using this.ServiceName
in a Windows Service written in C#? 如何在C#编写的Windows服务中使用
this.ServiceName
以编程方式获取服务名称? When I try this, it's asking for assembly reference but its not accepting anything: 当我尝试此操作时,它要求提供程序集引用,但不接受任何内容:
string path = this.ServiceName + ".config";
but its getting error. 但它得到错误。
Your service needs to inherit ServiceBase
from System.ServiceProcess.dll
. 您的服务需要从
System.ServiceProcess.dll
继承ServiceBase
。
When you will have that you will be able to access this.ServiceName
property. 当拥有时,您将能够访问
this.ServiceName
属性。
Sample: 样品:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
string test = this.ServiceName;
}
protected override void OnStop()
{
}
}
If you want to access it from Main() (Program class), then you can do something like this: 如果要从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);
}
}
}
To find the .config file for your service, do not use the service name. 要为您的服务找到.config文件,请不要使用服务名称。 That's not how the CLR works, it selects the .config file based on the EXE name.
这不是CLR的工作方式,它会根据EXE名称选择.config文件。 Fix:
固定:
var path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
To access the configuration file you need the application name not the service name (if you are using standard .Net application configuration files). 要访问配置文件,您需要应用程序名称而不是服务名称(如果使用的是标准.Net应用程序配置文件)。
To get the application executable use System.AppDomain.CurrentDomain.FriendlyName 要获取应用程序可执行文件,请使用System.AppDomain.CurrentDomain.FriendlyName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.