Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a GUID representing a user in Active Directory, how would I use this to determine the distinguished name?

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

like image 867
John Sibly Avatar asked Dec 17 '22 22:12

John Sibly


2 Answers

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.

like image 73
Rob Avatar answered Dec 19 '22 12:12

Rob


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.

like image 28
wanion Avatar answered Dec 19 '22 12:12

wanion