'Search Active Directory Group by GUID using DirectorySearcher

I'm using DirectorySearcher to find an AD security group by its (object) GUID.

Here's my code so far:

using (var container = new DirectoryEntry("LDAP://host:port/DC=X,DC=Y", User, Pass, AuthenticationType)
{
   using (var searcher = new DirectorySearcher(container))
   {
      searcher.Filter = $"(objectguid=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)"

      var result = searcher.FindOne();
   }
}

Unfortunately the result always returns null, and I cannot change the DirectoryEntry's path.



Solution 1:[1]

To make a query using objectGuid requires a special format that I don't quite remember right now, but it's complicated.

But there's a better way. You can bind directly to the object using the GUID, without searching, by using this format:

var result = new DirectoryEntry("LDAP://host:port/<GUID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX>", User, Pass, AuthenticationType)

More information on that here: Using objectGUID to Bind to an Object

You can do the same with the SID as well: Binding to an Object Using a SID

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriel Luci