Using the DirectorySearcher class, you can find specific Active Directory objects. The following is an example of searching the Active Directory for the user account Administrator.
using System;
using System.DirectoryServices;
using System.Windows.Forms;
namespace UnumTest
{
public class CloseClass
{
static void Main(string[] args)
{
try
{
DirectoryEntry oRoot = new DirectoryEntry("LDAP://RootDSE");
string searchOU =
(string)oRoot.Properties["defaultnamingcontext"].Value;
DirectoryEntry de =
new DirectoryEntry("LDAP://CN=Users," + searchOU);
Console.WriteLine(oRoot.Name);
oRoot.Close();
DirectorySearcher search = new DirectorySearcher(de);
search.Filter = "(CN=Administrator)";
search.PropertiesToLoad.Add("distinguishedName");
SearchResultCollection results = search.FindAll();
string strRet="Not Found";
foreach(SearchResult result in results)
{
DirectoryEntry data = result.GetDirectoryEntry();
strRet =
(string)data.Properties["distinguishedName"].Value;
Console.WriteLine(strRet);
data.Close();
}
de.Close();
results.Dispose()
//Required or you may leak TCP connections
}
catch(Exception e)
{
Console.WriteLine( e.Message);
}
}
}
}