GetCurrentUserSid


BOOL GetCurrentUserSid(std::string& strSID)
{
 CCommonFunc func;
 DWORD dwProcessID = func.GetProcessIDFromName("explorer.exe");
 if( 0 == dwProcessID )
 {
  return FALSE;
 }
#ifndef _RELEASE_WIN9X
 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessID);
 if( hProc == NULL )
 {
  return FALSE;
 }
 HANDLE hToken;
 if( !OpenProcessToken(hProc, TOKEN_QUERY, &hToken) )
 {
  CloseHandle(hProc);
  return FALSE;
 }
 CloseHandle(hProc);
 BOOL bRet = FALSE;
 TOKEN_USER *pTokenUser;
 DWORD Len;
 char* pBuffer = NULL;
 if( !GetTokenInformation(hToken, TokenUser, NULL, 0, &Len) )
 {
  if( GetLastError() ==  ERROR_INSUFFICIENT_BUFFER )
  {
   pBuffer = new char[Len];
   if( !GetTokenInformation(hToken,TokenUser, pBuffer, Len, &Len) )
   {
    delete pBuffer;
    CloseHandle(hToken);
    return FALSE;
   }
  }
  else
  {
   CloseHandle(hToken);
   return FALSE;
  }
 }
 
 pTokenUser = (TOKEN_USER*)pBuffer;
 char *szStringSID;
 if( FALSE == ConvertSidToStringSid(pTokenUser->User.Sid, &szStringSID) )
 {
  CloseHandle(hToken);
  return FALSE;
 }
 else
 {
  strSID = szStringSID;
  //std::string strTemp = szStringSID;
  LocalFree(szStringSID);
  //strSID = strTemp;
 }
 CloseHandle(hToken);
 
#endif _RELEASE_WIN9X
 return TRUE;
}
posted @ 2009-03-12 11:35  ahuo  阅读(469)  评论(0编辑  收藏  举报