C
C#12mo ago
Ella

✅ Detect the user name who started the process

I need to get the user that started the process but I cannot find where to do this
No description
10 Replies
kurumi
kurumi12mo ago
isn't it what are you looking for?
No description
Ella
EllaOP12mo ago
yes, but i wanna get this info via C# code
kurumi
kurumi12mo ago
I see
Ella
EllaOP12mo ago
i forgot to mention the language, lol sorry
Anchy
Anchy12mo ago
Process.MachineName?
Ella
EllaOP12mo ago
nope, already tried that one
Anchy
Anchy12mo ago
what does that give you
Ella
EllaOP12mo ago
"." on every process
Ella
EllaOP12mo ago
lemme check Didn't make this link work Found this solution: Install Nuget package: System.Management
using System.Management;
...
public static string? GetProcessOwner(int processId)
{
string? MethodResult = null;
try
{
string Query = $"SELECT * FROM WIN32_PROCESS WHERE ProcessId = {processId}";

ManagementObjectCollection Processes = new ManagementObjectSearcher(Query).Get();

foreach (ManagementObject Process in Processes.Cast<ManagementObject>())
{
string[] Args = ["", ""];

int ReturnCode = Convert.ToInt32(Process.InvokeMethod("GetOwner", Args));

MethodResult = ReturnCode switch
{
0 => Args[1] + "\\" + Args[0],
_ => "NONE",
};
}

}
catch (Exception ex)
{
MessageBox.Show($"Error geting process owner: \n{ex.Message}");
}
return MethodResult;
}
using System.Management;
...
public static string? GetProcessOwner(int processId)
{
string? MethodResult = null;
try
{
string Query = $"SELECT * FROM WIN32_PROCESS WHERE ProcessId = {processId}";

ManagementObjectCollection Processes = new ManagementObjectSearcher(Query).Get();

foreach (ManagementObject Process in Processes.Cast<ManagementObject>())
{
string[] Args = ["", ""];

int ReturnCode = Convert.ToInt32(Process.InvokeMethod("GetOwner", Args));

MethodResult = ReturnCode switch
{
0 => Args[1] + "\\" + Args[0],
_ => "NONE",
};
}

}
catch (Exception ex)
{
MessageBox.Show($"Error geting process owner: \n{ex.Message}");
}
return MethodResult;
}

Did you find this page helpful?