Sunday, 11 August 2013

Active Directory search filter with ObjectGuid

   We can use different type of Active Directory attributes with ldap filter easily such as string, int and datetime based attributes like name, lastlogon, mail, etc.. But when we force to use attribute which has syntax like byte [], MultiValued and uniqueidentifier, we will face some difficulties to form ldap search filter. Here, I have written an example about how to use objectguid in Active Directory search filter.  

Note: You can refer this article to know about ldap search filters.

static class Program
        static void Main()

        private static string GetObjectNameByGUID()
            string userObjectGuid = "AC56F9F3-C11C-456F-92B1-5FAFFB493A6D";

            DirectoryEntry dirEntry = new DirectoryEntry("LDAP://DC=Work2008,DC=local");
            DirectorySearcher directorySearcher = new DirectorySearcher(dirEntry,
               string.Format("((objectguid={0}))", GetBinaryStringFromGuid(userObjectGuid)));
            directorySearcher.CacheResults = false;
            directorySearcher.Tombstone = true;

            SearchResult searchResult = directorySearcher.FindOne();

            return searchResult.Properties["name"][0].ToString();

        private static string GetBinaryStringFromGuid(string guidstring)
            Guid guid = new Guid(guidstring);

            byte[] bytes = guid.ToByteArray();

            StringBuilder sb = new StringBuilder();

            foreach (byte b in bytes)
                sb.Append(string.Format(@"\{0}", b.ToString("X")));

            return sb.ToString();

Related Articles:

Active Directory Attribute mapping with Friendly name - user
Active Directory Search Filter Examples
Create new Active Directory User in C#
How to get list of all domain controllers in C#
Remote Group Policy update using gpupdate in C#
Restore a deleted Active Directory object using C#

Software Developer


No comments:

Post a Comment