How can I get the SID of the current Windows account?

后端 未结 11 1142
面向向阳花
面向向阳花 2020-12-14 01:02

I am looking for an easy way to get the SID for the current Windows user account. I know I can do it through WMI, but I don\'t want to go that route.

Apologies to ev

11条回答
  •  被撕碎了的回忆
    2020-12-14 01:32

    And in native code:

    function GetCurrentUserSid: string;
    
        hAccessToken: THandle;
        userToken: PTokenUser;
        dwInfoBufferSize: DWORD;
        dw: DWORD;
    
        if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, ref hAccessToken) then
            dw <- GetLastError;
            if dw <> ERROR_NO_TOKEN then
                RaiseLastOSError(dw);
    
            if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, ref hAccessToken) then
                RaiseLastOSError;
        try
            userToken <- GetMemory(1024);
            try
                if not GetTokenInformation(hAccessToken, TokenUser, userToken, 1024, ref dwInfoBufferSize) then
                    RaiseLastOSError;
                Result <- SidToString(userToken.User.Sid);
            finally
                FreeMemory(userToken);
        finally
            CloseHandle(hAccessToken);
    

提交回复
热议问题