Last active
June 27, 2019 09:22
-
-
Save SamKr/5c809fa0d8676a214d4cb7924def89d0 to your computer and use it in GitHub Desktop.
Get the owner of a process, without using slow WMI calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [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