Tuesday, October 10, 2017

SharePoint 2010 - How to check if group exists without exception

The SharePoint Server handles some things differently than you might know from standard C # programs.
I recently stumbled upon that I've tried to determine if a user group exists in SharePoint. I thought no problem and tried it with this code:

string nameOfGroupToCheck = "Test Group";
SPGroup group = spWeb.Groups[nameOfGroupToCheck];
if(group != null) {
   ...
}

I assumed that the variable group is null if the group is not present, but SharePoint throws an exception instead.
This does not happen with the following code snippet:

using System.Linq;
...
string nameOfGroupToCheck = "Test Group";
if (spWeb.Groups.OfType<SPGroup>().Where(g => g.Name == nameOfGroupToCheck).Count() > 0)
{
  ...
}

To get this code work correctly, you need to add the System.Linq namespace into your code.

By the way, this check also works with lists in SharePoint. You would only have to query the lists instead of the groups.


No comments:

Post a Comment