我该如何找回Windows服务正在运行下的用户名? [英] How do I retrieve the username that a Windows service is running under?
问题描述
给定一个服务名称,我想找回用户名,这下(即在'登录'的服务的属性窗口的选项卡中显示的用户名)运行。似乎没有要在的ServiceController
类东西来获取这些基本信息。闲来无事在 System.ServiceProcess
看起来要么公开此信息。是否有一个管理的解决方案,这一点,还是我将不得不向下拖放到的东西的低级?
Given a service name, I would like to retrieve the username that it runs under (i.e. the username shown in the 'Log On' tab of a service's properties window). There doesn't appear to be anything in the ServiceController
class to retrieve this basic information. Nothing else in System.ServiceProcess
looks like it exposes this information either. Is there a managed solution to this, or am I going to have to drop down into something lower-level?
推荐答案
使用WMI与System.Management你可以试试下面的代码:
Using WMI, with the System.Management you can try the following code:
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();
}
}
}
您可后来与您的服务名称来替代注释代码,它应该只返回正在运行的服务进程的实例。
You can then later substitute the commented code with your service name, and it should only return the instances of your service process that is running.
这篇关于我该如何找回Windows服务正在运行下的用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!