David Browne wrote:
|| ||| Strahimir Antoljak wrote:
||||| Is there a way to find out the name
||||| of the user who created a process.
||||| Some kind of process property or method
||||| that would report the user name how launched
||||| it?
||||| (but not Environment.UserName)
|||||
||||| Thanks,
|||||
||||| --
||||| Strah
|||
||| There is no support for this in the FCL.
||| Your only option is to PInvoke (or MC++)
||| 1. call the Win32 'OpenProcessToken' Win32 API using the
||| 'Process.Handle' property as the first argument
||| 2. use the tokenHandle returned to call WindowsIdentity(tokenHandle)
||| 3. WindowsIdentity.Name should contain the process owner.
||| 4. Close the tokenHandle using the 'CloseHandle' Win32 API.
|||
||| Note that you will need special privileges to call OpenProcessToken,
|| consult the SDK docs for details.
||| Willy.
|||
|| Yikes. Sounds scarry.
||
Yes, it is
, another option is to use the System.Management (WMI) namespace.
|| Anyway there is a performance counter that will tell you this. It
No, it's not, OP asked for the user principal name of the creator of the process.
Here is how to do it in (C#)
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security.Principal;
using System.Diagnostics;
using System.Security;
// Problem: proc.Handle property returns Access denied for 'idle' process and,
// Cannot OpenProcessToken() for NT AUTHORITY\NETWORK SERVICE and NT AUTHORITY\LOCAL SYSTEM
// Better use - WTSEnumerateProcesses on XP and higher
//
using HANDLE = System.IntPtr;
class IdentUser {
[DllImport("advapi32", SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]
static extern int OpenProcessToken(
HANDLE ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);
[DllImport("kernel32", SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]
static extern bool CloseHandle(HANDLE handle);
public const int TOKEN_QUERY = 0X00000008;
public static void Main() {
Process[] _process = Process.GetProcesses();
foreach(Process proc in _process)
{
try {
Console.WriteLine("Process Name :{0} \tProcess ID : {1} ",
proc.ProcessName, proc.Id);
DumpPrincipalName(proc.Handle);
Console.WriteLine("--------------------------------------------------");
}
catch(Exception ex)
{Console.WriteLine("Exception: {0}", ex.Message);}
}
}
static void DumpPrincipalName(HANDLE processHandle)
{
int access = TOKEN_QUERY;
HANDLE tokenHandle = IntPtr.Zero;
if ( 0 != OpenProcessToken( processHandle, access, ref tokenHandle ) )
{
WindowsIdentity wi = new WindowsIdentity(tokenHandle);
Console.WriteLine(wi.Name);
CloseHandle(tokenHandle); // Close process token
}
else
Console.WriteLine("Error OpenProcessToken: {0}",Marshal.GetLastWin32Error());
}
}