How to determine the type of (AD User vs. AD Group) account?

I have a question about determining the type (user or group) of an account name.
For example, I have two lines, for example "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 determine the type (User or AD group) of this account? Is there any convenient way that I can use?

Any comments are welcome. Thanks.

+3
source share
1 answer

What version of .NET are you using?

.NET 3.5, . MSDN , Active Directory .

.NET 3.5, :

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
Principal myObject = Principal.FindByIdentity(ctx, "your name value");

, - - DOMAIN\USERNAME.

"" UserPrincipal, GroupPrincipal ( - , ComputerPrincipal):

if(myObject is UserPrincipal)
{
    // you have a user
}
else if(myObject is GroupPrincipal)
{
    // you have a group
}

.


.NET 1.x/2.0/3.0, DirectorySearcher :

// 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();
    }
}

+10

Source: https://habr.com/ru/post/1724705/


All Articles