After searching for a long time, I found an easy way to get a local user's
SID in string format. To do so in VB.NET, do the following:
1. Import the Interop Services namespace:
- Imports System.Runtime.InteropServices
2. Declare the ConvertSidToStringSid function:
- Private Declare Auto Function ConvertSidToStringSid Lib "advapi32.dll"
(ByVal bSID As IntPtr, <System.Runtime.InteropServices.In(),
System.Runtime.InteropServices.Out(),
System.Runtime.InteropServices.MarshalAs(System.Ru ntime.InteropServices.UnmanagedType.LPTStr)> ByRef SIDString As String) As Integer
3. Call the ConvertSidToStringSid function:
- Dim strSID As String = ""
Dim intSuccess As Integer
Dim user As New
System.DirectoryServices.DirectoryEntry("WinNT://Machine/User")
Dim sidBytes As Byte() = CType(user.Properties("objectsid").Value,
Byte())
Dim sidPtr As IntPtr =
System.Runtime.InteropServices.Marshal.AllocHGloba l(sidBytes.Length)
System.Runtime.InteropServices.Marshal.Copy(sidByt es, 0, sidPtr,
sidBytes.Length)
intSuccess = ConvertSidToStringSid(sidPtr, strSID)
txtSID.Text = strSID.Trim()
I hope this helps some people. It felt like pulling teeth finding this and
I'm glad I finally found a solution.