Friday, December 13, 2013

How to Add User to Default SharePoint Groups Programatically

As every SharePoint developer or user know that when a new Site is created, Obviously 3 commonly used site specific groups will be created automatically along with some general groups.
<Site Name> Owners
<Site Name> Members
<Site Name> Visitors

To add an user to any of the above three groups of a site, we have a API method to get the groups associated with that site, programatically.
using (SPSite site = new SPSite("http://siteurl"))
{
    using (SPWeb web = site.RootWeb)
    {
        ////Get the site default groups
        SPGroup owernsGroup = web.AssociatedOwnerGroup;
        SPGroup membersGroup = web.AssociatedMemberGroup;
        SPGroup visitorsGroup = web.AssociatedVisitorGroup;

        ////Add user to groups
        SPUser user = web.EnsureUser("login");
        if (null != user)
        {
            owernsGroup.AddUser(user);
            membersGroup.AddUser(user);
            visitorsGroup.AddUser(user);
        }
    }
}

Also we can add user to other default groups like Approvers, Designers and Viewers etc., But there is no API property for web to get these groups. So we can get the group by Name.
if (web.GroupExists("Approvers"))
{
    ////Get approvers group
    SPGroup approversGroup = web.Groups["Approvers"];            
    if (null != approversGroup)
    {
        ////Add user to group
        SPUser user = web.EnsureUser("login");
        approversGroup.AddUser(user);
    }
}

No comments:

Post a Comment