How can a Windows Service determine its ServiceName?

后端 未结 7 834
春和景丽
春和景丽 2020-11-27 05:53

I\'ve looked and couldn\'t find what should be a simple question:

How can a Windows Service determine the ServiceName for which it was started?

相关标签:
7条回答
  • 2020-11-27 06:55

    From: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024

    Here is a WMI solution. Overriding the ServiceBase.ServiceMainCallback() might also work, but this seems to work for me...

        protected String GetServiceName()
        {
            // Calling System.ServiceProcess.ServiceBase::ServiceNamea allways returns
            // an empty string,
            // see https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024
    
            // So we have to do some more work to find out our service name, this only works if
            // the process contains a single service, if there are more than one services hosted
            // in the process you will have to do something else
    
            int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
            String query = "SELECT * FROM Win32_Service where ProcessId = " + processId;
            System.Management.ManagementObjectSearcher searcher =
                new System.Management.ManagementObjectSearcher(query);
    
            foreach (System.Management.ManagementObject queryObj in searcher.Get()) {
                return queryObj["Name"].ToString();
            }
    
            throw new Exception("Can not get the ServiceName");
        } 
    
    0 讨论(0)
提交回复
热议问题