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