Monthly Archives: December 2010

Retrieving user SID using DirectoryEntry and DirectorySearcher

Recently I was working on one of main projects that amongst other things retrieves some user properties from Active Directory.

In order to use Exchange 2007 Webservices I needed to retrieve the SID because the SID was needed when impersonating a given user. This articke describes how to retrieve the SID into a byte array and using P/Invoke.

Step 1 – Search the AD

    1 public SearchResultCollection getUserInfo(string ldapPath)

    2         {

    3             string ADUserName = ConfigurationManager.AppSettings[“UserName”];

    4             string ADPassword = ConfigurationManager.AppSettings[“Password”];

    5             DirectoryEntry rootEntry = new DirectoryEntry(ldapPath, ADUserName, ADPassword);

    6             DirectorySearcher searcher = new DirectorySearcher(rootEntry);

    7             //add the properties to retrieve

    8             //accountstatus

    9             searcher.PropertiesToLoad.Add(“userAccountControl”);

   10             //mail

   11             searcher.PropertiesToLoad.Add(“mail”);

   12             searcher.PropertiesToLoad.Add(“accountExpires”);

   13             searcher.PropertiesToLoad.Add(“proxyaddresses”);

   14             searcher.PropertiesToLoad.Add(“SAMAccountName”);

   15             searcher.PropertiesToLoad.Add(“objectSid”);

   16             SearchResultCollection results;

   17             results = searcher.FindAll();

   18             return results;

   19         }


Step 2 – loop the SearchResultCollection retriveing the “objectSid”

    string sidStringValue=””;

    foreach (SearchResult result in src)


                  //reset SID

                  byte[] SID = null;

                  if (result.Properties[“objectSid”].Count > 0)


                      SID = (byte[]) result.Properties[“objectSid”][0];


                  sidStringValue = GetSidString(SID); 

             }//end foreach

Step 3 – In the code example above a call to the method “GetSidString” is made – this method looks like this:

        [DllImport(“advapi32”, CharSet = CharSet.Auto, SetLastError = true)]

        static extern bool ConvertSidToStringSid([MarshalAs(UnmanagedType.LPArray)] byte[] pSID, out IntPtr ptrSid);


        public static string GetSidString(byte[] sid)


            IntPtr ptrSid;

            string sidString;

            if (!ConvertSidToStringSid(sid, out ptrSid))

                throw new System.ComponentModel.Win32Exception();



                sidString = Marshal.PtrToStringAuto(ptrSid);






            return sidString;



Retrieve SID from domain user

I do a lot of Exchange development and integrations. Doing that I often need to use a specific users SID. From the Exchange Management Console the SID can’t be retrieved easily. I have found a tool, that makes the task of fetching a user SID very easy. It is called GetSid  and you can download it from here: