Test Whether SPUser Is In SPGroup
I had to write a small method this morning that would allow me to test whether an SPUser object was a member of an arbitrary SPGroup. Particularly, I needed a way to do this in an event receiver, which is why you see a reference to the properties parameter representative of the SPItemEventProperties when getting a reference to the relevant item and list objects. I wanted to do this basically:
-
SPUser curUser = web.CurrentUser;
-
-
SPGroup testGroup = properties.ListItem.Web.Groups["Home Visitors"];
-
string groupName = testGroup.Name;
-
if (bIsInGroup(curUser, groupName))
-
{
-
-
-
}
Then to use this boolean test, I simply just used this method:
-
private bool bIsInGroup(SPUser user, string strname)
-
{
-
try
-
{
-
foreach (SPGroup group in user.Groups)
-
{
-
if (group.Name == strname)
-
return true;
-
}
-
}
-
catch (Exception exception)
-
{
-
WriteLogEvent(string.Format("An Error Occured | Exception Message:{0} StackTrace: {1}", exception.Message, exception.StackTrace));
-
}
-
return false;
-
}
And just using the traditional way of writing errors to the event log:
-
public void WriteLogEvent(string strmessage)
-
{
-
// Create a new event comLog object
-
-
// Check whether the event comLog source already exists
-
if (!EventLog.SourceExists("test"))
-
EventLog.CreateEventSource("test", "Application");
-
-
// Specify the source for the exception message
-
comLog.Source = "test";
-
// Write the entry to the event comLog
-
comLog.WriteEntry(strmessage);
-
}
Related posts:
- Testing Whether A User Has SPBasePermission On SPList Object
- Get SPGroup, If Not Available, Create!
- Remember to Elevate For Event Log Entries
- Should You Test SharePoint GUID’s?
- WebPart Exception / Error Handling
3 Comments »
RSS feed for comments on this post. TrackBack URL























Articles & Research
SharePoint Architecture
Research Methodology
Personal/Off-Topic
Article Or Research Filed Under 

Hi Adam,
I’ve looked into this too at the following article: http://chrissyblanco.blogspot.com/2007/07/determining-whether-user-is-member-of.html
I looked at doing it your way i.e iterating the Groups collection of the SPUser object, however this didn’t appear to work for the following scenario:
Say you have a user who is a member of an AD group e.g. ADGroupX. You then add ADGroupX to a SharePoint group (SPGroup), say SharePointGroupY.
If you iterate the Groups collection of the SPUser object for the user who is a member of ADGroupX then SharePointGroupY is not one of the SPUser.Groups . . .
Have you seen this issue too ?!
Many thanks,
Chris
Comment by Chris White — August 8, 2007 @ 1:08 am
Just had to say thanks. This is a concise solution to a problem I was fighting against.
Comment by Rob — December 7, 2008 @ 1:30 pm
i want to check the selected user’s group how would i??(i have a list of users in a dropdown)
Comment by santosh — April 9, 2009 @ 7:56 am