Retrieve information from AD
By Anatoly Mironov
Here is a a link you can start with. To test AD, install AD. Then we canplay with it. Take a look those examples, too.
PrincipalSearcher vs. DirectorySearcher
What is the difference?
OU
Here are two examples (one for PrincipalSearcher and the other for DirectorySearcher) to retrieve users from an OU:
//PrincipalSearcher
internal static void ListPrincipalsFromOu()
{
using(var ctx = new PrincipalContext(ContextType.Domain, "takana.local", "OU=SOME\_OU ,DC=takana, DC=local"))
{
using (var up = new UserPrincipal(ctx))
{
using (var ps = new PrincipalSearcher(up))
{
using (var res = ps.FindAll())
{
foreach (var p in res)
{
Console.WriteLine(p.SamAccountName);
}
}
}
}
}
}
//DirectorySearcher
internal static void ListAdEntriesFromOu()
{
const string property = "sAMAccountName";
var ldapcon = new DirectoryEntry("takana.local") {
Path = "LDAP://OU=SOME\_OU,DC=takana,DC=local"
};
var search = new DirectorySearcher(ldapcon);
search.PropertiesToLoad.Add(property);
using (var results = search.FindAll())
{
foreach (System.DirectoryServices.SearchResult result in results)
{
using (var entry = result.GetDirectoryEntry())
{
if (entry.Properties\[property\].Count > 0)
{
Console.WriteLine(entry.Properties\[property\]\[0\]);
}
}
}
}
}