Click here to Skip to main content
15,126,367 members
Articles / Programming Languages / C#
Posted 15 Jul 2006


53 bookmarked

How To Get Process Owner ID and Current User SID

Rate me:
Please Sign up or sign in to vote.
4.52/5 (14 votes)
15 Jul 2006CPOL1 min read
The article explains how to get the process owner ID and current user SID


The article explains how to get process owner ID and current user SID. It's useful when you develop Terminal Server applications. There are two main ways to get process owner SID by process ID (PID):

  1. Using Windows Management Instrumentation (WMI). It's the slowest way to get info.
  2. Using the Win32 API.

How To Get Process Owner SID using WMI

The shortest and slowest way to get process owner SID is to use WMI. The code is very simple and there are no comments needed.

public static string GetProcessInfoByPID(int PID, out string User, out string Domain)
    User = String.Empty;
    Domain = String.Empty;
    OwnerSID = String.Empty;
    string processname = String.Empty;
        ObjectQuery sq = new ObjectQuery
            ("Select * from Win32_Process Where ProcessID = '" + PID + "'");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq);
        if (searcher.Get().Count == 0)
            return OwnerSID;
        foreach (ManagementObject oReturn in searcher.Get())
            string[] o = new String[2];
            //Invoke the method and populate the o var with the user name and domain
            oReturn.InvokeMethod("GetOwner", (object[])o);

            //int pid = (int)oReturn["ProcessID"];
            processname = (string)oReturn["Name"];
            //dr[2] = oReturn["Description"];
            User = o[0];
            if (User == null)
                User = String.Empty;
            Domain = o[1];
            if (Domain == null)
                Domain = String.Empty;
            string[] sid = new String[1];
            oReturn.InvokeMethod("GetOwnerSid", (object[])sid);
            OwnerSID = sid[0];
     return OwnerSID;
        return OwnerSID;
    return OwnerSID;

How To Get Process Owner SID using Win32 API

The Win32 API way is a little bit complicated, but works far better (faster).

public const int TOKEN_QUERY = 0X00000008;

const int ERROR_NO_MORE_ITEMS = 259;

enum TOKEN_INFORMATION_CLASS                           
    TokenUser = 1,

static extern bool OpenProcessToken(
    HANDLE ProcessHandle, // handle to process
    int DesiredAccess, // desired access to process
    ref IntPtr TokenHandle // handle to open access token

static extern HANDLE GetCurrentProcess();

[DllImport("advapi32", CharSet = CharSet.Auto)]
static extern bool GetTokenInformation(
    HANDLE hToken,
    IntPtr TokenInformation,
    int tokeInfoLength,
    ref int reqLength

static extern bool CloseHandle(HANDLE handle);

[DllImport("advapi32", CharSet = CharSet.Auto)]
static extern bool ConvertSidToStringSid(
    IntPtr pSID,
    [In, Out, MarshalAs(UnmanagedType.LPTStr)] ref string pStringSid

[DllImport("advapi32", CharSet = CharSet.Auto)]
static extern bool ConvertStringSidToSid(
    [In, MarshalAs(UnmanagedType.LPTStr)] string pStringSid,
    ref IntPtr pSID

/// <span class="code-SummaryComment"><summary></span>
/// Collect User Info
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="pToken">Process Handle</param></span>
public static bool DumpUserInfo(HANDLE pToken, out IntPtr SID)
    int Access = TOKEN_QUERY;
    HANDLE procToken = IntPtr.Zero;
    bool ret = false;
    SID = IntPtr.Zero;
        if (OpenProcessToken(pToken, Access, ref procToken))
            ret = ProcessTokenToSid(procToken, out SID);
        return ret;
    catch (Exception err)
        return false;

private static bool ProcessTokenToSid(HANDLE token, out IntPtr SID)
    TOKEN_USER tokUser;
    const int bufLength = 256;            
    IntPtr tu = Marshal.AllocHGlobal(bufLength);
    bool ret = false;
    SID = IntPtr.Zero;
        int cb = bufLength;
        ret = GetTokenInformation(token, 
                TOKEN_INFORMATION_CLASS.TokenUser, tu, cb, ref cb)
        if (ret)
            tokUser = (TOKEN_USER)Marshal.PtrToStructure(tu, typeof(TOKEN_USER));
            SID = tokUser.User.Sid;
        return ret;
    catch (Exception err)
        return false;

public static string ExGetProcessInfoByPID
    (int PID, out string SID)//, out string OwnerSID)
    IntPtr _SID = IntPtr.Zero;                                       
    SID = String.Empty;                                             
        Process process = Process.GetProcessById(PID);
        if (DumpUserInfo(process.Handle, out _SID))
            ConvertSidToStringSid(_SID, ref SID);
        return process.ProcessName;                                          
        return "Unknown";

How To Get Current User SID

How to use information about owner SID? Imagine a simple situation when you should show a list of current user processes. This is a typical thing when you develop some application to use on the Terminal Server, where a lot of users work with applications with the same name.

private WindowsIdentity _user = WindowsIdentity.GetCurrent();


public bool IsCurrentUserProcess(int ProcessID)
    string stringSID = String.Empty;
    string process = Utils.ExGetProcessInfoByPID(ProcessID, out stringSID);
    return String.Compare(stringSID, this._user.User.Value, true) == 0);


This is just a small sample of what WMI could do. Unfortunately WMI works quite slowly, so for now, there isn't a faster way to get the needed info than using the Win32 API.



  • 16th July, 2006: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
Russian Federation Russian Federation
I am a CIO in Nizhny Novgorod, Russia.

Comments and Discussions

GeneralMy vote of 1 Pin
Sean McArdle3-Apr-14 8:25
MemberSean McArdle3-Apr-14 8:25 
SuggestionC++ sample Pin
Jeest29-Sep-11 4:38
MemberJeest29-Sep-11 4:38 
GeneralRe: C++ sample ( other similar code) Pin
dmihailescu24-Jan-12 8:52
Memberdmihailescu24-Jan-12 8:52 
GeneralMy vote of 3 Pin
Andromeda Shun16-Sep-11 3:45
MemberAndromeda Shun16-Sep-11 3:45 
QuestionGet Process Name (process info) of Active Window Pin
Ali Taghvajou31-Mar-11 9:53
professionalAli Taghvajou31-Mar-11 9:53 
General[My vote of 1] Copied code HANDLE SID [modified] Pin
Chuck14117-Sep-10 12:14
MemberChuck14117-Sep-10 12:14 
Generalwhen i run the InvokeMethod("GetOwner", object[])o); Pin
cholo12349-Mar-10 7:36
Membercholo12349-Mar-10 7:36 
GeneralRe: when i run the InvokeMethod("GetOwner", object[])o); Pin
laxmanchip22-Jul-10 9:13
Memberlaxmanchip22-Jul-10 9:13 
GeneralRe: when i run the InvokeMethod("GetOwner", object[])o); Pin
laxmanchip22-Jul-10 9:37
Memberlaxmanchip22-Jul-10 9:37 
GeneralAn alternate method Pin
efwb0016-Nov-09 9:37
Memberefwb0016-Nov-09 9:37 
GeneralNone of them works Pin
Member 33345068-Mar-09 8:13
MemberMember 33345068-Mar-09 8:13 
GeneralRe: None of them works Pin
Naked Coder6-Sep-09 4:11
MemberNaked Coder6-Sep-09 4:11 
QuestionHANDLE?? Pin
tfwarlord18-Dec-08 14:10
Membertfwarlord18-Dec-08 14:10 
AnswerRe: HANDLE?? Pin
bergdoktor25-Mar-09 5:04
Memberbergdoktor25-Mar-09 5:04 2005 Translation Pin
rerb11-Jun-07 4:57
Memberrerb11-Jun-07 4:57 
GeneralRe: 2005 Translation Pin
rerb11-Jun-07 8:00
Memberrerb11-Jun-07 8:00 
GeneralClever Pin
Jared Hill26-Mar-07 17:21
MemberJared Hill26-Mar-07 17:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.