Sunday, May 27, 2018

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

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

 var emailId = string.Empty;

 string activeDirectory_LDAP = "LDAP://server";

 string activeDirectory_User = "ad_username";

 string activeDirectory_Password = "ad_password";

 var directoryEntry = new DirectoryEntry(activeDirectory_LDAP, activeDirectory_User, activeDirectory_Password) { AuthenticationType = AuthenticationTypes.Secure };

 var directorySearcher = new DirectorySearcher(directoryEntry);

 directorySearcher.Filter = "sAMAccountName=" + userName;

 directorySearcher.SearchScope = SearchScope.Subtree;



 SearchResult searchResult = directorySearcher.FindOne();

 if (searchResult != null)

 {

  emailId = searchResult.GetDirectoryEntry().Properties["email"].Value.ToString();

 }



 return emailId;

}

No comments:

Post a Comment