Given a GUID representing a user in Active Directory, how would I use this to determine the user's "distinguished name" using C#?
The GUID is retrieved earlier in our application using directoryEntry.Guid; MSDN Link
As you've made it clear a GUID is what you're searching on, try this:
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;
}
}
I've used this with IdentityType.Name
so can't be sure it'll work for IdentityType.Guid
, but it's worth a try.
You can get the distinguishedName from the DirectoryEntry directly:
public string GetDN(DirectoryEntry de)
{
return de.Properties["distinguishedName"].Value.ToString();
}
If you still need to bind via GUID you can do that as well:
public string GetDNviaGUID(Guid queryGuid)
{
DirectoryEntry de = new DirectoryEntry("LDAP://<GUID=" + queryGuid + ">");
return de.Properties["distinguishedName"].Value.ToString();
}
The following properties and methods don't work when you bind via GUID or SID: ADsPath, Name, Parent, GetObject, Create, Delete, CopyHere, MoveHere.
You can get around this by retrieving the object via GUID, getting its distinguished name, and then binding using the DN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With