Reputation: 218
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.
Upvotes: 1
Views: 11029
Reputation: 1916
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.
Upvotes: 2
Reputation: 14376
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 ([email protected]).
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.
Upvotes: 0