Question

I am getting crazy here, I'd really appreciate some help! simply I want to get user name or anything from Active Directory using DirectoryEntry class.

I used userprinciple and it works great, but the property I need to get (user's manager) is only avaliable in DirectoryEntry.

My problem is, I looked so much online and I got the codes from there, but for some reason it never works, always return Null. here is an example :

public static DirectoryEntry GetUser(string UserName)
{
    //create an instance of the DirectoryEntry
    DirectoryEntry de = new DirectoryEntry("LDAP://" + "OU=AnotherOU,OU=xx,OU=Testvironments,DC=abc,DC=local");

    //create instance fo the direcory searcher
    DirectorySearcher deSearch = new DirectorySearcher(de);

    deSearch.SearchRoot = de;
    //set the search filter
    deSearch.Filter = "(&(objectCategory=user)(cn=" + UserName + "))";
    //deSearch.SearchScope = SearchScope.Subtree;

    //find the first instance
    SearchResult results = deSearch.FindOne();

    //if found then return, otherwise return Null
    if (results != null)
    {
        //de= new DirectoryEntry(results.Path,ADAdminUser,ADAdminPassword,AuthenticationTypes.Secure);
        //if so then return the DirectoryEntry object
        return results.GetDirectoryEntry();
    }
    else
    {
        return null;
    }
}

I have no clue why this code returns null.

Thanks in advance.

Was it helpful?

Solution

You can try like this

//create instance for directory entry
DirectoryEntry de = new DirectoryEntry("LDAP://" + "OU=AnotherOU,OU=xx,OU=Testvironments,DC=abc,DC=local");

//create instance fo the directory searcher
DirectorySearcher deSearch = new DirectorySearcher(de );;

//set the search filter
deSearch.Filter = "(&(objectClass=user)(|(SAMAccountName=" + UserName+ ")(givenName=" + UserName+ ")(name=" + UserName+ ")(SN=" + UserName+ "))";

//find the first instance
SearchResult results = deSearch.FindOne();

//if found then return, otherwise return Null
if (results != null)
{
    //The desired property you want , you can extract in this way.
   DomainName = results .Properties["SamAccountName"][0].ToString();
   return domainName
}
else
{
    return null;
}

Hope this is what you are looking for.

OTHER TIPS

Do you want the cn, samAccountname, displayName or userPrincipalName attributes? samAccountName is the traditional (NT 4.0) style user name, displayName is usually first name plus last name and the userPrincipalName is in a similar format to an E-mail address (user@domain.name).

Either way, if you want to test out different queries, use an interactive LDAP query tool like ldp.exe. It will probably be much easier than trying them out in code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top