简体   繁体   中英

AD GroupPrincipal: Exception has been thrown by target of invocation

I am able to run the following code as this user with no problems under all other circumstances. For some reason, in this one particular case, while adding users to a group and checking prior to see if the user is already added, it gives me this exception:

Exception has been thrown by target of an invocation.

This error occurs at the invoke line.

This should not be happening. The directory object sent is correct, the group exists, I can remove members from it just fine, I can even add members to it without checking as a test. In other areas of my app this code is used without error. I use this code in many other apps and have been using it for years. What's going on here? What am I forgetting?

private bool userIsMember(string strUser, DirectoryEntry strGroup)
{
    bool result = true;
    try
    {
        object[] args = { strUser };
        object IsMember = strGroup.Invoke("IsMember", args);

        if ((bool)IsMember == true)
        {
            result = true;
        }
        else
        {
            result = false;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Problem with user: " + strUser + "\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.ToString());
    }

    return result;
}

If it worked in other applications, then my guess as to why it isn't working here is something different in the credentials of the user running this code (in other words, security).

But regardless, if you can, I would switch to use the classes in System.DirectoryServices.AccountManagement. They are much more C# friendly:

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, "GName");

The GroupPrincipal has a Members property you can search through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM