我正在寻找名为“MyApp.exe”的进程,我想确保获得特定用户拥有的进程。
我使用以下代码获取进程列表:
Process[] processes = Process.GetProcessesByName("MyApp");
这给了我一个进程列表,但是在Process类中似乎没有办法确定谁拥有该进程?有关如何做到这一点的任何想法?
答案 0 :(得分:60)
您可以使用WMI让用户拥有某个进程。要使用WMI,您需要在项目中添加对System.Management.dll
的引用。
按流程ID:
public string GetProcessOwner(int processId)
{
string query = "Select * From Win32_Process Where ProcessID = " + processId;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
return argList[1] + "\\" + argList[0];
}
}
return "NO OWNER";
}
按流程名称(仅查找第一个流程,相应调整):
public string GetProcessOwner(string processName)
{
string query = "Select * from Win32_Process Where Name = \"" + processName + "\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
string owner = argList[1] + "\\" + argList[0];
return owner;
}
}
return "NO OWNER";
}
答案 1 :(得分:22)
由于WMI并不总是快速检索信息的方式,因此这是本机P / Invoke的方式:
不成功时返回值为null
。为了获得在SYSTEM用户下运行的进程的名称,您需要以管理员身份执行此代码。
private static string GetProcessUser(Process process)
{
IntPtr processHandle = IntPtr.Zero;
try
{
OpenProcessToken(process.Handle, 8, out processHandle);
WindowsIdentity wi = new WindowsIdentity(processHandle);
string user = wi.Name;
return user.Contains(@"\") ? user.Substring(user.IndexOf(@"\") + 1) : user;
}
catch
{
return null;
}
finally
{
if (processHandle != IntPtr.Zero)
{
CloseHandle(processHandle);
}
}
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
答案 2 :(得分:7)
以下是非C#发言人的VB版本:
Function GetProcessOwner(ProcessName As String) As String
Dim query = "Select * from Win32_Process Where Name = """ + ProcessName + """"
Dim searcher = New ManagementObjectSearcher(query)
Dim processList = searcher.Get()
For Each obj As ManagementObject In processList
Dim argList As String() = {String.Empty, String.Empty}
Dim returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
' return DOMAIN\user
Dim owner = argList(1) + "\\" + argList(0)
Return owner
End If
Next
Return "NO OWNER"
End Function
Function GetProcessOwner(processId As Integer) As String
Dim query = "Select * From Win32_Process Where ProcessID = " & processId
Dim searcher = New ManagementObjectSearcher(query)
Dim processList = searcher.Get()
For Each obj As ManagementObject In processList
Dim argList As String() = {String.Empty, String.Empty}
Dim returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
If returnVal = 0 Then
' return DOMAIN\user
Return argList(1) + "\\" + argList(0)
End If
Next
Return "NO OWNER"
End Function
答案 3 :(得分:4)
不幸的是,没有原生的.Net方式来获取流程所有者。
看看这些可能的解决方案:
答案 4 :(得分:0)
添加对项目的引用:
System.Management
然后将以下方法添加到您的项目中:
public string GetProcessOwner(int processId)
{
string MethodResult = null;
try
{
StringBuilder sb = new StringBuilder();
sb.Append(" SELECT ");
sb.Append(" * ");
sb.Append(" FROM ");
sb.Append(" WIN32_PROCESS");
sb.Append(" WHERE ");
sb.Append(" ProcessId = " + processId);
string Query = sb.ToString();
ManagementObjectCollection Processes = new ManagementObjectSearcher(Query).Get();
foreach (ManagementObject Process in Processes)
{
string[] Args = new string[] { "", "" };
int ReturnCode = Convert.ToInt32(Process.InvokeMethod("GetOwner", Args));
switch(ReturnCode)
{
case 0:
MethodResult = Args[1] + "\\" + Args[0];
break;
default:
MethodResult = "None";
break;
}
}
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
然后添加此方法:
public DataTable GetProcessTable()
{
DataTable MethodResult = null;
try
{
List<Process> Processes = Process.GetProcesses().ToList<Process>();
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns["Name"].ReadOnly = true;
dt.Columns.Add("Id", typeof(string));
dt.Columns["Id"].ReadOnly = true;
dt.Columns.Add("Owner", typeof(string));
dt.Columns["Owner"].ReadOnly = true;
foreach (Process p in Processes)
{
DataRow r = dt.NewRow();
bool Match = false;
r["Id"] = p.Id.ToString();
r["Name"] = p.ProcessName;
r["Owner"] = GetProcessOwner(p.Id);
dt.Rows.Add(r);
}
MethodResult = dt;
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
调用GetProcessTable()为您提供所有正在运行的进程的DataTable及其Id和Name,这很方便,因为它可以用作DataGridView的Datasource参数。
如果您需要在表格中添加更多字段,请与我们联系。
答案 5 :(得分:0)
System.Security.Principal.WindowsIdentity.GetCurrent().Name
答案 6 :(得分:0)
@ bytecode77:
我现在仅通过查看代码就可以告诉您,您将生成潜在的FirstChanceExceptions…特别是由于这些“ .ACCESS DENIED”(Win32Exception)和“ NOT RUNNING”(ArgumentException)导致了。 'process.Handle'的表达式求值器阻止。
进程句柄是应用程序专用的-换句话说, 进程句柄无法共享。
另请参阅LinkDemand = 6和SecurityCriticalAttribute。
尽管您可能仍需要为此属性“工具->调试->启用Just My Code”,但仍然会引发FirstChanceExceptions。
除此之外,我确实同意您在pinvoke Win32调用中的回答比WMI更快,尤其是在所有进程进行迭代时。
[DebuggerNonUserCode]
private static IEnumerable<Process> GetProcesses() =>
Process.GetProcesses().Where(p => {
var hasException = false;
try {
var x = p.Handle;
} catch {
hasException = true;
}
return !hasException;
}).ToArray();
答案 7 :(得分:0)
var myApp = Process.GetProcessesByName("MyApp").FirstOrDefault();
if (myApp != null)
{
string username = GetUsername(myApp.SessionId);
}
方法GetUsername的实现:https://stackoverflow.com/a/35810391/10412686
答案 8 :(得分:0)
WMI实际上是从Process获取此信息的最糟糕的方法。但是...有时您需要从远程进程中获取该信息,在这种情况下,您可悲地需要WMI。因此,如果您必须或想使用WMI,我建议这样做(比上面的经典WMI方法快60%以上):
public struct WMIProcessProperties
{
public string Owner;
public int ID;
}
public static async Task<Dictionary<Process, WMIProcessProperties>> GetWMIProperties(this IEnumerable<Process> processes)
{
Dictionary<Process, WMIProcessProperties> result = new Dictionary<Process, WMIProcessProperties>();
if (processes == null || processes.Count() == 0) { return result; }
string selectQuery = "SELECT Handle, ProcessID FROM Win32_Process";
selectQuery += processes.Count() <= 10 ? string.Format(" WHERE ProcessID = {0}", string.Join(" OR ProcessID = ", processes.Select(p => p.Id))) : string.Empty;
using (CimSession session = await Task.Run(() => CimSession.Create(processes.ElementAt(0).MachineName)))
{
List<CimInstance> instances = await Task.Run(() => session.QueryInstances(@"root\cimv2", "WQL", selectQuery).ToList());
List<Task<WMIProcessProperties>> tasks = new List<Task<WMIProcessProperties>>();
for (int i = 0; i < instances.Count; i++)
{
CimInstance currentInstance = instances[i];
tasks.Add(Task.Run(() =>
{
int id = Convert.ToInt32(currentInstance.CimInstanceProperties["ProcessID"].Value);
string owner;
using (CimMethodResult getOwnerResult = session.InvokeMethod(currentInstance, "GetOwner", null))
{
owner = getOwnerResult.OutParameters["User"]?.Value?.ToString();
}
currentInstance.Dispose();
return new WMIProcessProperties { Owner = owner, ID = id };
}));
}
WMIProcessProperties[] wmiProcessProperties = await Task.WhenAll(tasks).ConfigureAwait(false);
for (int i = 0; i < wmiProcessProperties.Length; i++)
{
result.Add(processes.Single(p => p.Id == wmiProcessProperties[i].ID), wmiProcessProperties[i]);
}
}
return result;
}
如果您想比较一点时间,请参阅answer。
答案 9 :(得分:0)
循环遍历集合以检查权限。 大多数情况下当前用户不是管理员
List<Process> processes = Process.GetProcessesByName(Text).ToList();
for (int i = processes.Count - 1; i > -1; i--)
{
try
{
if (processes[i].MainModule?.FileName is null)
processes.RemoveAt(i);
}
catch (Exception)
{
processes.RemoveAt(i);
}
}
答案 10 :(得分:-1)
这是我发现的最简单方法:
Process[] processes = Process.GetProcessesByName("MyApp");
foreach (Process process in processes)
{
string username = process.StartInfo.Environment["USERNAME"];
// do some stuff
}