This method does not care what the objectclass is and will work for verifying users, OUs, groups etc. It's just verifying the dn is legit.
public static bool Exists(string dn)
{
var domain = "sf.sp.edu.sg";
var ldapSearchFilter = "(objectClass=*)";
SearchResponse response = null;
using (var connection = new LdapConnection(domain))
{
try
{
var request = new SearchRequest();
request.Filter = ldapSearchFilter;
//dn = OU=Users,OU=AHSC,DC=sf,DC=sp,DC=edu,DC=sg for this example
request.DistinguishedName = dn;
request.Scope = SearchScope.Base;
response = (SearchResponse)connection.SendRequest(request);
}
catch (Exception ex)
{
//handle errors here
}
}
return (response.Entries.Count > 0);
}
Realized after posting that you want all the OUs with Users. Not sure if you want all the objects or just the names, but here is how you can get all of the dns for those OUs
var ds = new DirectorySearcher();
ds.Filter = "(&(objectClass=organizationalUnit)(ou=Users))";
ds.PropertiesToLoad.Add("distinguishedName");
ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
ds.FindAll();
var dnList = new List<string>();
foreach (SearchResult ou in ous)
{
dnList.Add(ou.Properties["distinguishedName"][0].ToString());
}