How to overcome & ldquo; The member's SID could not be resolved & rdquo; Error checking if user is member of group?


We have a process that requires to check whether a particular user is a member of local Administrators group.

The code that checks that looks like the following:

using (PrincipalContext context = new PrincipalContext(ContextType.Machine, null))
    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, sUserName);
    if (user != null)
         SecurityIdentifier adminsGroupSID = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
         GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.Sid, adminsGroupSID.Value);
         if (group != null)
             if (user.IsMemberOf(group))
                 return 0;

When the group has accounts (e.g. domain accounts) that were removed, we're getting a PrincipalOperationException and a message "An error (1332) occurred while enumerating the group membership. The member's SID could not be resolved."

Is there any way to overcome this without: a) Removing manually the orphaned SIDs from the group b) Not ignoring it?


One way to avoid the error is to go other way around. Instead of checking if an user is member of a group, retrieve first all the groups and check the list for your target group. One drawback: is slower....

var groups = UserPrincipal.Current.GetAuthorizationGroups();
var found = groups.FirstOrDefault(principal => principal.Name == "Administrators");
var isMemberOfAdminGroup = found != null;

Thanks arus for your help :)