Monday, November 14, 2011

Get all security group names using SharePoint object model

In this post we will discuss about how to get all security group names using SharePoint object model.

Also you can check out:

- Delete custom page layout in SharePoint 2010

- Enable Sign in as Different User Option in SharePoint 2013

- SharePoint: Custom Media Video Player using JQuery

You can get the security group names using SharePoint object model by using the SPGroup class.

Here is the code below:

using (SPSite siteCollection = new SPSite("Ur Site collection URL"))
{
using(SPWeb site = siteCollection.OpenWeb)
{
foreach(SPGroup group in site.Groups)
{
string groupName=group.Name;
}
}
}

It will give you all the group names available in the current site inside the site collection. Also one thing to remember is that you can not create a Group at the site level, always you have to create in the Site collection.

The below code shows how to add a group to a site collection:

site.SiteGroups.Add("NewSecurityGroup",site.CurrentUser,site.CurrentUser,"A new group");