在.NET中获取进程的用户名或所有者,可以使用System.Diagnostics.Process类。以下是一个简单的示例代码:
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
try
{
string processName = process.ProcessName;
string processOwner = GetProcessOwner(process);
Console.WriteLine($"Process Name: {processName}, Owner: {processOwner}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
static string GetProcessOwner(Process process)
{
string query = $"SELECT UserName FROM Win32_Process WHERE ProcessId = {process.Id}";
using (var searcher = new ManagementObjectSearcher(query))
{
using (var results = searcher.Get())
{
foreach (ManagementObject result in results)
{
return result["UserName"].ToString();
}
}
}
return "Unknown";
}
}
这段代码首先使用Process.GetProcesses()方法获取所有进程,然后遍历每个进程并调用GetProcessOwner()方法获取进程的用户名。GetProcessOwner()方法使用WMI查询来获取进程的用户名。最后,将进程名称和用户名输出到控制台。
领取专属 10元无门槛券
手把手带您无忧上云