What version of .NET are you on??
If you're on .NET 3.5, see this excellent MSDN article on how the Active Directory interface has changed quite a bit.
If you're on .NET 3.5, you could write:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
Principal myObject = Principal.FindByIdentity(ctx, "your name value");
Typically, you'd have to pass in just the user name - the part after the backslash - not the whole DOMAIN\USERNAME string.
This "Principal" now either is a UserPrincipal
or a GroupPrincipal
(or it could some other type of principal, e.g. ComputerPrincipal
):
if(myObject is UserPrincipal)
{
// you have a user
}
else if(myObject is GroupPrincipal)
{
// you have a group
}
and you can go on from there.
If you're on .NET 1.x/2.0/3.0, you'd have to use the slightly more involved procedure of creating a DirectorySearcher
and searching for your object:
// create root DirectoryEntry for your search
DirectoryEntry deRoot = new DirectoryEntry("LDAP://dc=YourCompany,dc=com");
// create searcher
DirectorySearcher ds = new DirectorySearcher(deRoot);
ds.SearchScope = SearchScope.Subtree;
// define LDAP filter - all you can specify is the "anr" (ambiguous name
// resolution) attribute of the object you're looking for
ds.Filter = string.Format("(anr={0})", "YourNameValue");
// define properties you want in search result(s)
ds.PropertiesToLoad.Add("objectCategory");
ds.PropertiesToLoad.Add("displayName");
// search
SearchResult sr = ds.FindOne();
// check if we get anything back, and if we can check the "objectCategory"
// property in the search result
if (sr != null)
{
if(sr.Properties["objectCategory"] != null)
{
// objectType will be "Person" or "Group" (or something else entirely)
string objectType = sr.Properties["objectCategory"][0].ToString();
}
}
Marc