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.
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.