lookup user in ActiveDirectory by email address
I don't know if I am missing something here, but finding an AD user from an e-mail address can be done much simpler:
var context = new PrincipalContext(ContextType.Domain);
var userPrincipal = UserPrincipal.FindByIdentity(context, emailAddress);
You can search your AD with following code:
DirectoryEntry adEntry = null;
private void SetADInfoAndCredentials()
{
adEntry = new DirectoryEntry("LDAP://" + ad_textBox.Text);
adEntry.Username = user_textBox.Text;
adEntry.Password = pw_textBox.Text;
}
private void SearchForMailInAD()
{
DirectorySearcher adSearcher = new DirectorySearcher(adEntry);
adSearcher.Filter = ("mail=" + mail_textBox.Text);
SearchResultCollection coll = adSearcher.FindAll();
foreach (SearchResult item in coll)
{
foundUsers_listBox.Items.Add(item.GetDirectoryEntry());
}
}
€: This will search for the mail address in proxyAddresses which hosts all mail addresses
public static SearchResultCollection FindAccountByEmail(string pEmailAddress)
{
string filter = string.Format("(proxyaddresses=SMTP:{0})", email);
using (DirectoryEntry gc = new DirectoryEntry("LDAP:"))
{
foreach (DirectoryEntry z in gc.Children)
{
using (DirectoryEntry root = z)
{
using (DirectorySearcher searcher = new DirectorySearcher(root, filter, new string[] { "proxyAddresses", "objectGuid", "displayName", "distinguishedName" }))
{
searcher.ReferralChasing = ReferralChasingOption.All;
SearchResultCollection result = searcher.FindAll();
return result;
}
}
}
}
return null;
}