Converting objectSid to string

I was writing a tool yesterday that involved mucking with Active Directory and such. During the process I realized that I needed to save the objectSid of the user for later use. AD defines this property as “Octet string” saved as bytes. Following the general wisdom and internet advices to convert this byte array into proper Sid did not work.

A little more digging and I found a simple class in .Net framework - SecurityIdentifier

MSDN defines this class as “Represents a security identifier (SID) and provides marshaling and comparison operations for SIDs.”

At this point, it becomes a simple matter of instantiating this class and calling ToString:

 private static string ConvertSidToString(byte[] objectSid)
{
    SecurityIdentifier si = new SecurityIdentifier(objectSid, 0);
    return si.ToString();
}

Happy coding!