Question

I need to find whether a OrganisationUnit has node Users. Below is a sample of ActiveDirectory.

enter image description here

For example OU=AHSC is having sub node OU=Users Then i want to copy the Object Name of OU=Users which is something like this - OU=Users,OU=AHSC,DC=sf,DC=sp,DC=edu,DC=sg

I want all OU which has subnodes OU=Users

I tried to achieve with DirectorySearcher, i am able to read entire data in AD but i want only OU with subnode OU=Users.

Hope I am clear.

Was it helpful?

Solution

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());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top