Check if a user already exists in Active Directory group

Check if a user already exists in Active Directory group:

Note: To add or read properties from an Active Directory group you need to have special username and password like an Active Directory admin.

DirectoryEntry addGroup;
string folderPath = "LDAP://CN=" + folderName + ",";
folderPath += "OU=SharedFolder,OU=Groups,DC=aaaaa,DC=com";

string usrId = “myUserID”;

addGroup = new DirectoryEntry(folderPath, "Spluser""password");

protected bool chkUserExistence(DirectoryEntry addGroup, string usrId)
    {
        bool usrExists = false;
        object allMembers = addGroup.Invoke("members"null);
        foreach (object member in (IEnumerable)allMembers)
        {
            DirectoryEntry memberEntry = new DirectoryEntry(member);
            if (usrId == memberEntry.Name.ToString())
            {
                usrExists = true;
                break;
            }
        }
        return usrExists;
    }

Leave your comments below.

No comments: