Free Trial Issue of Visual Studio Magazine

VB5, VB6 Get the User SID
Private Function GetSid()As Long
Const FIRST_ATTEMPT As Long = 16&
Dim lngToken As Long
Dim atypTokenInfo()As TOKEN_USER
Dim lngLength As Long
Dim lngRtn As Long
If OpenProcessToken (GetCurrentProcess, _
    TOKEN_QUERY, lngToken) Then
   If lngToken <> 0 Then
      ReDim atypTokenInfo (1 To _
         FIRST_ATTEMPT) As TOKEN_USER
      lngRtn = _
      GetTokenInformation (lngToken, _
      TokenUser, atypTokenInfo(1), _
      Len(atypTokenInfo(1)) * _
      FIRST_ATTEMPT, lngLength)
      If lngRtn <> 0 Then
         If atypTokenInfo _
            (1).uSid.pSid <> 0 Then
            GetSid = atypTokenInfo (1).uSid.pSid
         Else
            GetSid = 0&
         End If
      Else
         GetSid = 0&
      End If
   Else
      GetSid = 0&
   End If
Else
   GetSid = 0&
End If
If lngToken <> 0 Then
   CloseHandle lngToken
End If
End Function
Listing 3 | Getting the user SID for the user creating the error isn't absolutely necessary (App.LogEvent doesn't), but it adds a nice touch to your application logging. Three API calls and the atypTokenInfo type variable seems like a lot of work, but you have to create them only one time.