DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

How to Add User to SharePoint Group programmatically

By Ashok Nalam on 21 May 2013 | Category: Sharepoint | Tagged: user groups 
In this snippet we will see how to add an user to SharePoint group programmatically.
  Discuss Add Comment   |  
Add rating Rate this resource   

Below code can be used to add an user to SharePoint group. AddUserToSPGroup method accepts  3 parameters as SPSite object, LoginName of the user and Group name.

//adds user to SPGroup
public static void AddUserToSPGroup(SPSite site, string userLoginName, string groupName)
{
    //Executes this method with Full Control rights even if the user does not have Full Control
     SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (SPWeb spWeb = site.RootWeb)
            {
                try
                {
                    spWeb.AllowUnsafeUpdates = true;//Allows updating web
                    SPUser spUser = spWeb.EnsureUser(userLoginName);
			//check user and group exists in web
                    	if (spUser != null && CheckGroupExistsInSiteCollection(spWeb, groupName))
			{
				SPGroup spGroup = spWeb.Groups[groupName];
				if (spGroup != null)
					spGroup.AddUser(spUser);
                        }
                }
                catch (Exception)
                {
                    //exception handling
                }
                finally
                {
                    spWeb.AllowUnsafeUpdates = false; //Even Exception occurs it set back to false
                }
            }
        });
}
//checks group exists in site collection
private static bool CheckGroupExistsInSiteCollection(SPWeb web, string groupName)
{
  return web.SiteGroups.OfType<SPGroup>().Count(g => g.Name.Equals(groupName, StringComparison.InvariantCultureIgnoreCase)) > 0;
}

Method call :

SPSite currentSite = SPContext.Current.Site;
SPUser loginName = "Domain\LoginName";
AddUserToSPGroup(currentSite,loginName,"Group Visitors")

Output: 

Adds "Domain\LoginName" user to "Group Visitors" group

Explanation: 

In the code we are using

  • SPSecurity.RunWithElevatedPrivileges - excutes code with full control
  • AllowUnsafeUpdates to true - Because we are adding user to SPGroup so AllowUnsafeUpdates allow updates to the web

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9526  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys