ConvertSidToStringSid (advapi32)
Last changed: -14.140.20.18

.
Summary
The ConvertSidToStringSid function converts a security identifier (SID) to a string format suitable for display, storage, or transmission.

C# Signature:

[DllImport("advapi32", SetLastError=true)]
static extern bool ConvertSidToStringSid(byte [] pSID, ref IntPtr ptrSid);

VB Signature:

Declare Auto Function ConvertSidToStringSid Lib "advapi32.dll" (ByVal pSID() As Byte, _
   ByRef ptrSid As IntPtr) As Boolean

Notes:

Warning

As explained here, memory for the returned unmanaged string must be freed by calling LocalFree. Therefore, you must define the string as an IntPtr in managed code and call LocalFree yourself. Otherwise, the marshaler would call CoTaskMemFree which is not correct in this case.

Tips & Tricks:

Please add some!

Sample Code:

Public Shared Function ByteArrayToStringSid(ByRef bArray As Byte()) As String
   Dim ptrSID As IntPtr = Nothing

   Try
     Dim sSID As String = String.Empty

     If ConvertSidToStringSid(bArray, ptrSID) = True Then
       sSID = System.Runtime.InteropServices.Marshal.PtrToStringAuto(ptrSID)
     End If

     Return sSID
   Finally
     LocalFree(ptrSID)
   End Try
End Function

Alternative Managed API:

Do you know one? Please contribute it!

Documentation