Go Back

Converting Object Sid byte[] to Object Sid String

I am working on an asset/inventory software for our IT deparment to replace a somewhat dated access database that uses a lot of free text fields. During this process i wanted to make sure that I collected Active directory users into my own tables to persist an audit trail for each asset. Since active directory users get deleted eventually and there may be users with a Sam Account name that is the same as a previous employee I decided to story users by their Object Sid as the primary key. Unfortunately,  System.DirectoryServices.DirectorySearcher returns DirectoryEntry objects which contain the objectSid as an array of bytes (byte[]) which isn't very useful for a primary key nor for the human eye. People are more use to seeing something like S-21-5-29389828-1283920-1283901-12345 or something like that. So i did some research on it and came up with this unmanaged solution.



 
       [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool ConvertSidToStringSid(
            IntPtr sid,

            [In, Out, MarshalAs(UnmanagedType.LPTStr)] ref StringBuilder pStringSid);

StringBuilder sidString2 = new StringBuilder();
 
               
                byte[] bytes = user.ObjectSid;
                unsafe
                {
                    IntPtr ptr = Marshal.AllocHGlobal(bytes.Length);
 
                    for (int x = 0; x < bytes.Length; x++)
                    {
                        Marshal.WriteByte(ptr, x,bytes[x]);
                    }
                    ConvertSidToStringSid(ptr, ref sidString2);
                    Marshal.Release(ptr);
                }
 
Unfortunately, just after i got that written i found this Managed Solution!
http://www.netomatix.com/GetUserSid.aspx

Facebook DZone It! Digg It! StumbleUpon Technorati Del.icio.us NewsVine Reddit Blinklist Furl it!

Post a comment!
  1. Formatting options