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.

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

5 thoughts on “Searching for an email id in Active Directory using C#”

  1. it is not working in window 7 what to do
    “he specified domain either does not exist or could not be contacted.”
    i m getting this error again and again

    Like

Please share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.