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.
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.