How can I determine whether a user belongs to a member in a domain group? I checked a lot of information and shared the information below.
Userisgroupmember (userlogin, rolename) is used to determine whether a user is a domain member.
Note: Because domain groups are nested in other domain groups, traversal is required.
Code
Private Static String Adpath = " LDAP: // domain " ;
/**/ /// <Summary>
/// Determine whether a user is a domain member
/// </Summary>
/// <Param name = "userlogin"> User Name </Param>
/// <Param name = "rolename"> Domain group name </Param>
/// <Returns> </returns>
Private Static Bool Userisgroupmember ( String Userlogin, String Rolename)
{
Directoryentry entry = New Directoryentry (adpath );
Directorysearcher mysearcher = New Directorysearcher (entry );
Mysearcher. Filter = String . Format ( " (& (Objectclass = user) (samaccountname = {0 })) " , Userlogin );
Mysearcher. propertiestoload. Add ( " Memberof " );
Searchresult mysr = Mysearcher. findone ();
If (Mysr. properties. Count > 1 ) // Two attributes are returned, one is the built-in adspath, and the other is the propertiestoload loaded
{
String [] Memberof = New String [Mysr. properties [ " Memberof " ]. Count];
Int I = 0 ;
Foreach (Object mycoll In Mysr. properties [ " Memberof " ])
{
Memberof [I] = Mycoll. tostring (). substring ( 3 , Mycoll. tostring (). indexof ( " , " ) - 3 );
If (Memberof [I] = Rolename)
Return True ;
I ++ ;
}
// In fact, this layer of loop is a breadth-first algorithm, because considering that a person directly belongs to a security group is more likely, this is more efficient. if the following loop is placed in the IF esle above, the depth is given priority.
Foreach ( String Groupname In Memberof)
{
If(Memberisgroupmember (groupname, rolename ))
Return True;
}
}
Return False ;
}
Private Static Bool Memberisgroupmember ( String Groupname, String Rolename)
{
Bool Isfind = False ;
Directoryentry entry = New Directoryentry (adpath );
Directorysearcher mysearcher = New Directorysearcher (entry );
Mysearcher. Filter = String . Format ( " (& (Objectclass = Group) (CN = {0 })) " , Groupname );
Mysearcher. propertiestoload. Add ( " Memberof " );
Searchresult mysr = Mysearcher. findone ();
String Memberof;
Try
{
If (Mysr. properties. Count > 1 ) // Two attributes are returned, one is the built-in adspath, and the other is the propertiestoload loaded
{
Foreach (Object mycoll In Mysr. properties [ " Memberof " ])
{
Memberof = Mycoll. tostring (). substring ( 3 , Mycoll. tostring (). indexof ( " , " ) - 3 );
If (Memberof = Rolename)
{< br> isfind = true ;< br> Break ;< BR >}
Else If (Memberisgroupmember (memberof, rolename ))
{< br> isfind = true ;< br> Break ;< BR >}
}
}
}
Catch (Exception ex)
{}
Return Isfind;
}
References:
Http://www.cnblogs.com/zyk/archive/2004/11/02/59707.html