[DllImport("advapi32.dll", SetLastError=true)]
static extern bool ConvertStringSidToSid(
string StringSid,
out IntPtr ptrSid
);
Private Declare Auto Function ConvertSidToStringSid Lib "advapi32.dll" ( _
ByVal Sid As IntPtr, _
ByRef StringSid As IntPtr _
) As Boolean
None.
'BOOL ConvertSidToStringSid(
' PSID Sid,
' LPTSTR* StringSid
');
Please add some!
Dim Sid, SidPtr As IntPtr
Dim SidString As String
' convert the SID to a string
If Environment.Version.Major = 4 Then
SidString = ConvertSidToStringSidNT(Sid)
Else
If ConvertSidToStringSid(Sid, SidPtr) = False Then
Exit Sub
End If
SidString = Marshal.PtrToStringAuto(SidPtr)
Marshal.FreeHGlobal(SidPtr)
End If
'typedef struct _SID_IDENTIFIER_AUTHORITY {
' BYTE Value[6];
'} SID_IDENTIFIER_AUTHORITY, *PSID_IDENTIFIER_AUTHORITY;
Structure SID_IDENTIFIER_AUTHORITY
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=6)> Dim Value() As Byte
End Structure
'BOOL IsValidSid(
' PSID pSid
');
Private Declare Function IsValidSid Lib "advapi32.dll" ( _
ByVal pSid As IntPtr _
) As Boolean
'PSID_IDENTIFIER_AUTHORITY GetSidIdentifierAuthority(
' PSID pSid
');
Private Declare Function GetSidIdentifierAuthority Lib "advapi32.dll" ( _
ByVal pSid As IntPtr _
) As IntPtr
'PUCHAR GetSidSubAuthorityCount(
' PSID pSid
');
Private Declare Function GetSidSubAuthorityCount Lib "advapi32.dll" ( _
ByVal pSid As IntPtr _
) As IntPtr
'PDWORD GetSidSubAuthority(
' PSID pSid,
' DWORD nSubAuthority
');
Private Declare Function GetSidSubAuthority Lib "advapi32.dll" ( _
ByVal pSid As IntPtr, _
ByVal nSubAuthority As Integer _
) As IntPtr
' a WinNT version of the ConvertSidToStringSid function
Function ConvertSidToStringSidNT(ByVal Sid As IntPtr) As String
Dim ans As String
Dim psia As SID_IDENTIFIER_AUTHORITY
Dim i, num, temp As Integer
Dim top As Long
Dim iptr As IntPtr
If Not IsValidSid(Sid) Then
Return ans
End If
ans = "S-1-"
' Get the top level authority
iptr = GetSidIdentifierAuthority(Sid)
psia = Marshal.PtrToStructure(iptr, GetType(SID_IDENTIFIER_AUTHORITY))
' How many sub authorities?
iptr = GetSidSubAuthorityCount(Sid)
num = Marshal.ReadInt16(iptr)
' hex version of the top authority?
If psia.Value(0) <> 0 And psia.Value(1) <> 0 Then
ans &= Hex(psia.Value(0))
ans &= Hex(psia.Value(1)).PadLeft(2, "0")
ans &= Hex(psia.Value(2)).PadLeft(2, "0")
ans &= Hex(psia.Value(3)).PadLeft(2, "0")
ans &= Hex(psia.Value(4)).PadLeft(2, "0")
ans &= Hex(psia.Value(5)).PadLeft(2, "0")
Else
top = psia.Value(5)
top += psia.Value(4) * 256
top += psia.Value(3) * 256 * 256
top += psia.Value(2) * 256 * 256 * 256
ans &= top.ToString
End If
For i = 0 To num - 1
iptr = GetSidSubAuthority(Sid, i)
temp = Marshal.ReadInt32(iptr)
ans &= "-" & temp.ToString
Next
Return ans
End Function