views:

111

answers:

1

I have a question about determining the type (User or Group) of a account name.
For example, I have two strings, say "Adventure-works\david" and "Adventure-works\admins", the first represents a user named david, and the second represents an AD group.

My question is how can I determin the type(User or AD group) of these account? Are there convenient method I can use?

Any comments are appreciated. Thanks.

+2  A: 

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

marc_s
Thanks for your post, it helps a lot. I'm using .NET 2.0. Even though, it takes more codes to finish this task, it works.
David DOU