Get Distinguished Name for a user
By Anatoly Mironov
To get the distinguished name for a user, it isn’t enough to get an SPUser object. The distinguished name is the unique string for identifying a user in Active Directory (eg. CN=BeforeDAfter,OU=Test,DC=North America,DC=Fabrikam,DC=COM) Even using UserProfile object is not that clear. The distinguished name can be found in a property which can be retrieved with brackets: up[PropertyConstants.DistinguishedName]
public static string GetDistinguishedName(string login)
{
var dn = "";
UserProfile up;
using (var site = new SPSite("http://dev"))
{
var serviceContext = SPServiceContext.GetContext(site);
var upm = new UserProfileManager(serviceContext);
var exists = upm.UserExists(login);
if (!exists)
upm.CreateUserProfile(login);
if (exists)
{
up = upm.GetUserProfile(login);
dn = up\[PropertyConstants.DistinguishedName\].Value.ToString();
}
}
return dn;
}
```The code is simplified and doesn't contain any error handling. And a better handling of upm.UserExists must be implemented: If upm.CreateUserProfile(login) runs, it doesn't make it so quickly and the next step won't run (upm.GetUserProfile). If you are not working in SP Context, you can see the distinguished name for a user in Powershell:
import-module activedirectory $u = get-aduser administrator $u.DistinguishedName