Skip to content

Instantly share code, notes, and snippets.

@SamKr
Last active June 27, 2019 09:22
Show Gist options
  • Select an option

  • Save SamKr/5c809fa0d8676a214d4cb7924def89d0 to your computer and use it in GitHub Desktop.

Select an option

Save SamKr/5c809fa0d8676a214d4cb7924def89d0 to your computer and use it in GitHub Desktop.
Get the owner of a process, without using slow WMI calls
[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);
internal static string GetProcessUser(Process process, bool includeDomain = false)
{
var processHandle = IntPtr.Zero;
try
{
OpenProcessToken(process.Handle, 8, out processHandle);
var wi = new WindowsIdentity(processHandle);
var user = wi.Name;
if (!includeDomain) return user.Contains(@"\") ? user.Substring(user.IndexOf(@"\") + 1) : user;
else return user;
}
catch
{
return null;
}
finally
{
if (processHandle != IntPtr.Zero)
{
CloseHandle(processHandle);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment