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#? When I try this, it's asking for assembly re开发者_运维问答ference but its not accepting anything:
string path = this.ServiceName + ".config";
but its getting error.
Your service needs to inherit ServiceBase
from System.ServiceProcess.dll
.
When you will have that you will be able to access this.ServiceName
property.
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:
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. That's not how the CLR works, it selects the .config file based on the EXE name. 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).
To get the application executable use System.AppDomain.CurrentDomain.FriendlyName
精彩评论