In WPF and therefore in the C# programming language, I am trying to use LDAP to find a specific user within an Active Directory. I was able to check if a specific user exists in an Active Directory but I was not able to retrieve that user from the directory in order to gain access to their properties.
I am using the System.DirectoryServices namespace.
Is there a way to do what I seek to achieve, is there a way to retrieve a specific user from the AD using LDAP in order to check their properties?
EDIT: code I used to check if user is in AD. Returns true if user is in AD, false if user is not found. I wonder thought if there is a limit to the number of users it will search.
bool ContainsUser(string domain, string userName)
{
string ldapBase = string.Format("LDAP://{0}", domain);
using (var entry = new DirectoryEntry(ldapBase))
{
using (var searcher = new DirectorySearcher(entry))
{
searcher.Filter = string.Format("(sAMAccountName={0})", userName);
return searcher.FindOne() != null;
}
}
}
You should investigate using UserPrincipal.FindByIdentity
for example:
public static string GetEmailAddressFromActiveDirectoryUserName(string adUserName)
{
string email = string.Empty;
if (!string.IsNullOrEmpty(adUserName))
{
using (var pctx = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal up = UserPrincipal.FindByIdentity(pctx, adUserName))
{
return !string.IsNullOrEmpty(up?.EmailAddress) ? up.EmailAddress : string.Empty;
}
}
}
return email;
}
See:
The code you use to check that the user exists in AD or not already loads user properties: searcher.FindOne()?.Properties
.
public class User
{
public string UserPrincipalName { get; set; }
public string Name { get; set; }
}
User GetAdUser(string domain, string userName)
{
string ldapBase = string.Format("LDAP://{0}", domain);
using (var entry = new DirectoryEntry(ldapBase))
{
using (var searcher = new DirectorySearcher(entry))
{
searcher.Filter = string.Format("(sAMAccountName={0})", userName);
var result = searcher.FindOne();
User user = null;
if (result != null)
{
// result.Properties - list of loaded user properties
// result.Properties.PropertyNames - list of user property names
user = new User
{
UserPrincipalName = result.Properties["userprincipalname"].Cast<string>().FirstOrDefault();
Name = result.Properties["name"].Cast<string>().FirstOrDefault();
}
}
return user;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.