Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在运行时在c#服务中获取windows服务名称?_C#_Windows_Service - Fatal编程技术网

如何在运行时在c#服务中获取windows服务名称?

如何在运行时在c#服务中获取windows服务名称?,c#,windows,service,C#,Windows,Service,我开始使用多个实例 sc <server> [command] [service name] <option1> <option2>... 没有成功。类似的东西怎么样。问题中的代码已经在调用该方法,那么您具体建议如何做?Process.GetCurrentProcess().ProcessNameSo是Process.GetCurrentProcess().ProcessName是Windows服务名称?ProcessName不能满足您的需要。您的初始代码应

我开始使用多个实例

sc <server> [command] [service name] <option1> <option2>...

没有成功。

类似的东西怎么样。

问题中的代码已经在调用该方法,那么您具体建议如何做?Process.GetCurrentProcess().ProcessNameSo是Process.GetCurrentProcess().ProcessName是Windows服务名称?ProcessName不能满足您的需要。您的初始代码应该可以正常工作,但是如果在服务运行之前调用它,它将没有有效的processid。也许试着叫它OnStart,我在这个OnStart中。启动相关事件后有什么事情吗?
    public static string getServiceName(int pid = 0)      
    {
        string result = "";

        System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher("root\\CIMV2", string.Format("SELECT * FROM Win32_Service where ProcessId={0}", pid));

        System.Management.ManagementObjectCollection moc = mos.Get();
        foreach (System.Management.ManagementObject mo in moc)
        {
            result = Convert.ToString(mo["Name"]);
        }

        return result;
    }

    getServiceName(System.Diagnostics.Process.GetCurrentProcess().Id)