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:
[csharp]

SPUser curUser = web.CurrentUser;

SPGroup testGroup = properties.ListItem.Web.Groups[“Home Visitors”];
string groupName = testGroup.Name;
if (bIsInGroup(curUser, groupName))
{

}

[/csharp]

Then to use this boolean test, I simply just used this method:

[csharp]

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;
}
[/csharp]

And just using the traditional way of writing errors to the event log:

[csharp]

public void WriteLogEvent(string strmessage)
{
// Create a new event comLog object
EventLog comLog = new EventLog(“Application”);

// 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);
}

[/csharp]

Share

3 thoughts on “Test Whether SPUser Is In SPGroup”

  1. 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

  2. i want to check the selected user’s group how would i??(i have a list of users in a dropdown)

Leave a Reply

Your email address will not be published. Required fields are marked *