Get distingushed name of the AD Logged user from the local computer?

28 Views Asked by At

Is it possible to get a distinguished name of the logged to AD user from the local computer? I mean I can retreive user's logged in ad info, as follow:

using System.DirectoryServices.ActiveDirectory;
using System.Security.Principal;
 AdFQDN = Domain.GetComputerDomain().Name;
 AdUserName = WindowsIdentity.GetCurrent().Name;

And it works perfectly fine, except I also need a distingushed name of the user in follwoing format:

CN=UserName,CN=Users,DC=DOMAIN,DC=com

I mean I can generate it from the AdUserName but it gonna be a quite hard coded, and not good practice as once I will move user to different OU, the whole logick will broke. So instead of hard coded generator I would like to have a proper name pulled localy, because anyway current user will be already logged in to the AD so I think this info should exist localy.

Also I know, that I can request that info via DomainServices lib, but this lib requres to have an opened context, which is also depends on "Distingushed name" so it is kind of infinte loop.

I would be very appreciate you if you could help me resolve this issue.

Thx in advance, Best regards, Maks.

2

There are 2 best solutions below

1
Andy Wynn On BEST ANSWER
using System.DirectoryServices.AccountManagement;

using (var context = new PrincipalContext(ContextType.Domain))
{
    var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Environment.UserName);

    if (userPrincipal != null)
    {
        return userPrincipal.DistinguishedName;
    }
}
return string.Empty;

Hopefully this should get you there.

0
Charlieface On

Not sure if it's more accurate to use the SID to search

using System.DirectoryServices.AccountManagement;

using var context = new PrincipalContext(ContextType.Domain);
var sid = WindowsIdentity.GetCurrent().User.Value;
var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.Sid, sid);
return userPrincipal?.DistinguishedName ?? "";