Sunday, January 20, 2013

SPWeb.Groups vs SPWeb.SiteGroups

When we programmatically work with user groups in SharePoint we have 2 options. Either to use SPWeb.Groups or SPWeb.SiteGroups. In this article I’ll explain the difference between those collections.

Before we start on the topic, you can read on basics of SharePoint user groups by referring to this post


SPWeb.SiteGroups will provide a collection that include all the security groups those are created within the same site collection.

On the other hand SPWeb.Groups collection will list all security groups those are referred (used) within the sub site (SPWeb object).

I’ll describe certain characteristics of each collection below

1. Can’t use SPWeb.Groups to add new groups

As mentioned in previous post, permission groups are created at the root (Site collection) level. Although it is possible to navigate to People and Groups section in sub site to create a group, that group will be originally created at the site collection level.

So the point to note is you can’t create a security group at the sub site level. You can easily understand the concept using code sample given below.


2. Use SPWeb.SiteGroups to create new group

In order to add the user group we need to use SPWeb.SiteGroups collection as shown below.

  1. //Create user group
  2. var login = @"dev\spadmin";
  3. var user = web.EnsureUser(login);
  4. var member = web.EnsureUser(login);
  5. web.SiteGroups.Add("Test Group", member, user, "");

3. A group is available in SPWeb.Groups collection only if that is referred within the web

To explain the concept I’ll print SPWeb.Groups and SPWeb.SiteGroups collections. Following is the result I got


As you can see, the “Test Group” we just created is not listed in the SPWeb.Groups collection. That is because it’s not being referred (used) within the site. Now we will break permission inheritance of a document library and add the same group to that


Now the Test Group is available in SPWeb.Groups collection.


No comments: