Sunday, May 27, 2018

How to get a value from Active Directory using C# PrincipalSearcher Class

Here is a sample C# program to get email id from active directory by username using PrincipalSearcher class.
using System.DirectoryServices.AccountManagement;
public string GetEmailIdFromActiveDirectory(string userName)
{
var emailId = string.Empty;

string activeDirectory_LDAP = "server";
string activeDirectory_User = "ad_username";
string activeDirectory_Password = "ad_password";

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, activeDirectory_LDAP);

bool isCredentialsValid = ctx.ValidateCredentials(activeDirectory_User, activeDirectory_Password);

if (isCredentialsValid)
{
UserPrincipal userPr = new UserPrincipal(ctx);
userPr.SamAccountName = userName;

PrincipalSearcher srchUser = new PrincipalSearcher(userPr);
UserPrincipal foundUsr = srchUser.FindOne() as UserPrincipal;

if (foundUsr != null)
{
emailId = foundUsr.Email;
}
}

return emailId;
}

No comments:

Post a Comment