C# – LDAP connection to Active Directory & Retrieve User Information

1. LDAP connection
2. Search by user id
3. Retrieve all the information from Active Directory

Sample code


using System;
using System.DirectoryServices;

namespace ActiveDirectory
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter user: ");
String username = Console.ReadLine();

try
{
// create LDAP connection object

DirectoryEntry myLdapConnection = createDirectoryEntry();

// create search object which operates on LDAP connection object
// and set search object to only find the user specified

DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(SamAccountName=" + username + ")";

// create results objects from search object

SearchResult result = search.FindOne();

if (result != null)
{

ResultPropertyCollection fields = result.Properties;

foreach (String ldapField in fields.PropertyNames)
{

foreach (Object myCollection in fields[ldapField])
{
if (ldapField == "userprincipalname" || ldapField == "displayname" || ldapField == "name" || ldapField == "mail" || ldapField == "company" || ldapField == "title" || ldapField == "lastlogon" || ldapField == "cn" || ldapField == "mobile")
{
Console.WriteLine(String.Format("{0,-20} : {1}",ldapField, myCollection.ToString()));

}

//to read the whole collection
//Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString()));

}
}
Console.ReadLine();
}

else
{
// user does not exist
Console.WriteLine("User not found!");
Console.ReadLine();
}
}

catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
Console.ReadLine();
}
}

static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = new DirectoryEntry();
ldapConnection.Path = "LDAP://YOUR-AD-URL";
ldapConnection.Username = "USERNAME";
ldapConnection.Password = "PASSWORD";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
}
}

Note
Add reference to system.DirectoryServices

Leave a Reply

Your email address will not be published. Required fields are marked *