Searching for an email id in Active Directory using C#

These are the steps i followed
1) Created a new windows application.
2) Added reference to System.DirectoryServices dll
3) Added a textbox(where the email id will be entered) and a button in the form.
4) On btnClick this is the code i wrote

we use the DirectorySearcher class to query the directory and read the attributes of the objects found
DirectorySearcher Dsearch = new DirectorySearcher();
EmailID = txtEmailID.Text;

The filter in an LDAP query restricts the objects that the search will return. It is the equivalent of the WHERE clause


Dsearch.Filter = “(&(objectCategory=person)(sAMAccountName=*)(mail=”+EmailID+”))”;
objectCategory=This attribute is meant to be used to group common types of objects together so that we can search across all of them. Both user and contact classes share the same objectCategory value of person.
sAMAccountName =To separate users from contacts efficiently we can make user of sAMAccountName attribute
mail =Finally the mail attribute is the attribute which we looking for. Setting it to the value entered in the textbox by the user

SearchResult sResult = Dsearch.FindOne();


A SearchResult represents a single item from a result set.The FindOne method returns a single SearchResult, representing the first result in the underlying result set. Internally, this method is calling the FindAll method and returning the first SearchResult from the SearchResultCollection

if (sResult != null)
{
txtInfo.Content = “This email id already existing”;
}
else
{
txtInfo.Content = “This email id is not found”;
}

That’s it.