C# 如何检索运行Windows服务的用户名?

C# 如何检索运行Windows服务的用户名?,c#,authentication,windows-services,C#,Authentication,Windows Services,给定一个服务名称,我想检索它运行的用户名(即服务属性窗口的“登录”选项卡中显示的用户名) ServiceController类中似乎没有任何东西可以检索此基本信息。System.ServiceProcess中的任何其他内容看起来都不会公开此信息 是否有一个托管的解决方案,或者我必须降到较低的级别?尝试以下方法: System.Security.Principal.WindowsIdentity.GetCurrent(); 但最明显的是,您将获得本地系统或网络。无法显示此用户的原因-该服务可以管

给定一个服务名称,我想检索它运行的用户名(即服务属性窗口的“登录”选项卡中显示的用户名)

ServiceController
类中似乎没有任何东西可以检索此基本信息。
System.ServiceProcess
中的任何其他内容看起来都不会公开此信息

是否有一个托管的解决方案,或者我必须降到较低的级别?

尝试以下方法:

System.Security.Principal.WindowsIdentity.GetCurrent();
但最明显的是,您将获得本地系统或网络。无法显示此用户的原因-该服务可以管理多个用户(由桌面共享、连接到当前windows会话、使用共享资源…)
系统启动服务,但任何用户都可以使用它。

WMI是您的朋友。请特别查看
StartName
属性。您可以通过从C#访问WMI


如果您以前没有使用过WMI,这篇文章似乎是一个很好的教程。

使用WMI,在System.Management中,您可以尝试以下代码:

using System;
namespace WindowsServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Management.SelectQuery sQuery = new System.Management.SelectQuery(string.Format("select name, startname from Win32_Service")); // where name = '{0}'", "MCShield.exe"));
            using (System.Management.ManagementObjectSearcher mgmtSearcher  = new System.Management.ManagementObjectSearcher(sQuery))
            {
                foreach (System.Management.ManagementObject service in mgmtSearcher.Get())
                {
                    string servicelogondetails =
                        string.Format("Name: {0} ,  Logon : {1} ", service["Name"].ToString(), service["startname"]).ToString();
                    Console.WriteLine(servicelogondetails);
                }
            }
            Console.ReadLine();
        }
    }
}

然后,您可以用服务名称替换注释后的代码,它应该只返回正在运行的服务流程的实例。

此解决方案对我来说很好:

    ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + this.ServiceName + "'");
    wmiService.Get();
    string user = wmiService["startname"].ToString();

您可以使用Windows注册表,读取以下字符串值,将
[SERVICE\u NAME]
替换为Windows服务的名称来查找:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[SERVICE_NAME]\ObjectName

然后,您可以获取从上述命令返回的WindowsIdentity对象的Name属性。-1这将返回当前用户而不是指定服务的
WindowsIdentity
。@pwnistein一如既往的服务是从系统或网络凭据启动的,而不是从“登录”用户启动的。请参阅我对此的编辑。因此,请澄清您想要获得启动服务的系统帐户(我的答案是正确的)或当前登录用户列表,这可能会使用此服务?通常服务作为本地系统或网络服务运行,但您可以安装一个以标准用户帐户运行的服务(我正在处理的项目中就是这样做的)。我不确定您是否理解我的意图:我想获取某个特定服务运行时使用的用户名。我希望从一个完全独立的客户机应用程序(即,检索用户名的所有代码都在客户机中)执行此操作。您对用户的建议将不起作用,因为根据MSDN,它“返回表示当前Windows用户的WindowsIdentity对象”。在这种情况下,它将是运行客户端应用程序的当前Windows用户的WindowsIdentity,不是服务的WindowsIdentity。请添加一些解释和答案,说明此答案如何帮助解决当前问题
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[SERVICE_NAME]\ObjectName