Home » Active Directory » How to fetch data from Active Directory from your .NET application?

How to fetch data from Active Directory from your .NET application?

By using System.DirectoryServices namespace, you can easily send LDAP queries to your Active Directory and return attribute values.

Make sure that LDAP port is open between your machine and the Active Directory server (Default port is 389 and Global Catalog query port is 3268. You may use another port if it is specified in your DirectoryEntry method)

string displayName = "";
string username = "AD username";

DirectoryEntry oDirectoryEntry = new DirectoryEntry("LDAP://AD-server");
DirectorySearcher oDirectorySearcher=new DirectorySearcher(oDirectoryEntry);

SearchResult oSearchResult = null;

try
{
   oDirectorySearcher.Filter = "(&(objectClass=user)(sAMAccountName=" +username+ ")) ";
   oSearchResult = oDirectorySearcher.FindOne();

   if (oSearchResult != null && oSearchResult.Properties.Contains("displayName"))
   {
      displayName = oSearchResult.Properties["displayName"][0].ToString();
   }
}
catch (Exception ex)
{
   // Error handling
}

References

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

1 thought on “How to fetch data from Active Directory from your .NET application?”

Leave a Comment