How can a Windows Service determine its ServiceName?

后端 未结 7 922
春和景丽
春和景丽 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:46

    Short version with Linq

      int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
      ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service where ProcessId = " + processId);
      ManagementObjectCollection collection = searcher.Get();
      var serviceName = (string)collection.Cast().First()["Name"];
    

提交回复
热议问题