Reputation: 411
Working with Active directory in an ASP.net CORE MVC website,
I can get many user property like diplayName, emailAdress...
But I cannot find the departement of the user.
Get user informations :
UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), Environment.UserName);
But user haven't a property "Department".
I've try :
DirectoryEntry directoryEntry = user.GetUnderlyingObject() as DirectoryEntry;
var property = "department";
if (directoryEntry.Properties.Contains(property))
{
var dep = directoryEntry.Properties[property].Value.ToString();
}
No departement property neither.
EDIT
Here's a list of properties available : "objectClass, cn, sn, title, description, userCertificate, givenName, distinguishedName, instanceType, whenCreated, whenChanged, displayName, uSNCreated, memberOf, uSNChanged, proxyAddresses, homeMDB, mDBUseDefaults, mailNickname, name, objectGUID, userAccountControl, badPwdCount, codePage, countryCode, badPasswordTime, lastLogon, pwdLastSet, primaryGroupID, objectSid, accountExpires, logonCount, sAMAccountName, sAMAccountType, showInAddressBook, legacyExchangeDN, userPrincipalName, objectCategory, dSCorePropagationData, lastLogonTimestamp, textEncodedORAddress, mail and Lot of msExchange"
Upvotes: 0
Views: 3321
Reputation: 3
To search for an employee's unit
Use value
Department = directoryEntry.Properties["subdivision"].Value as string,
Upvotes: 0
Reputation: 109852
This works for me (using a mixture of AccountManagement
and DirectoryServices
):
var ad = new PrincipalContext(ContextType.Domain, DOMAIN);
var u = new UserPrincipal(ad) {SamAccountName = Environment.UserName};
using (var search = new PrincipalSearcher(u))
{
var user = (UserPrincipal) search.FindOne();
DirectoryEntry dirEntry = (DirectoryEntry)user.GetUnderlyingObject();
string dept = dirEntry.Properties["Department"].Value.ToString();
Console.WriteLine(dept);
}
This requires the following using
:
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
Upvotes: 6