Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

How can i check if a user (not the current user) exists in a group. The SPGroup object allows to check if the current user is member of the group, but there is no method that checks if a SPUser given in parameter exists or not.

Someone has any idea ?

share|improve this question

5 Answers 5

I use an extension method, like this:

    public static bool InGroup(this SPUser User, string GroupName)
    {
        return User.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == GroupName.ToLower());
    }

Then call it like this:

bool inGroup = spuser.InGroup("GroupName");
share|improve this answer

I think you have to look at the SPUser instead of the SPGroup: SPUser has a Groups collection you can iterate and look for the group name.

Something like:

foreach ( SPGroup group in user.Groups )
    if ( group.Name == groupName )
        // found it
share|improve this answer
1  
In terms of scalability this is a better solution as you could have groups with potentially large numbers of users, but a user is unlikely to be a member of so many groups. Its a minor point, but everything helps right? –  Charles Lee Mar 10 '10 at 9:37
    
Thats a pretty good point Charles. I posted my answer before I saw Anders. Maybe the decision will also include whether you already have an SPGroup/SPUser to iterate? –  Nick Hadlee Mar 10 '10 at 9:40
    
You can find some nifty helper methods for this in SPExLib: spexlib.codeplex.com/SourceControl/changeset/view/22718#339608 –  Wictor Wilen MCA MCM MVP Mar 10 '10 at 11:46

you could try SPGroup.ContainsCurrentUser, after having opened your SPSite with the SPUserToken of your target user.

share|improve this answer
    
ContainsCurrentUser is good only when you want to check the current logged in user. This will not help Alex. He will have to check the SPUser.Gropus collection. –  Sudhir Kesharwani Aug 30 '11 at 13:35
2  
I suggested to open the SPSite with the SPUserToken of the target user. This should set the "Current User" context to the target user. –  Jaap Vossers Sep 1 '11 at 13:49
    
You are my hero. –  boflynn Jun 27 '12 at 14:48

The SPGroup has a Users property which is a SPUser collection. Why not just loop through that and look for the SPUser that way?

share|improve this answer
    
This will have performance issues, since a group can contain many number of users, This will result in looping many times to check one user. consider using SPUser.Group collection instead. –  Sudhir Kesharwani Aug 30 '11 at 13:36

For a client-side JavaScript solution, this article describes how to determine if a not-current-user is a member of a group. http://chrissyblanco.blogspot.com/2007/07/determining-whether-user-is-member-of.html

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.