I'm searching users on Active Directory using System.DirectoryServices.AccountManagement.
Here' a simple example
using System;
using System.DirectoryServices.AccountManagement;
public static class DomainHelpers
{
public string GetDistinguishedName(string domain, string guid)
{
var context = new PrincipalContext(ContextType.Domain, domain);
var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.Guid, guid);
return userPrincipal.DistinguishedName;
}
}
The userPrincipal is always null. If I change IdentityType.Guid to IdentityType.SamAccountName and search for the samaccountname, it works just fine. If I take the guid property of that userPrincipal object that I got when searching for the samAccountName, I once again get no response.
Any ideas what I need to do to get results using the guid? I'm under the distinct impression that a couple years back when I wrote this code, it used to work just fine. But back then I had Windows 2008 R2 as DCs, now I have Windows 2016.
If I access the DirectoryEntry directly, so using
using (DirectoryEntry entry = new DirectoryEntry($"LDAP://{DomainName}/<GUID={objectGuid}>"))
Things work as expected. So it's a problem inherent with `UserPrincipal.FindIdentity'. I also tried supplying the NativeGuid to FindByIdentity, but it doesn't change things a bit.