Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

Add a user programmatically to a User Group in SharePoint

/// <summary>
        /// Add a user to a Sharepoint group
        /// </summary>
        /// <param name="userLoginName">Login name of the user to add</param>
        /// <param name="userGroupName">Group name to add</param>
        private void AddUserToAGroup(string userLoginName, string userGroupName)
        {
            //Executes this method with Full Control rights even if the user does not otherwise have Full Control
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                //Don't use context to create the spSite object since it won't create the object with elevated privileges but with the privileges of the user who execute the this code, which may casues an exception
                using (SPSite spSite = new SPSite(Page.Request.Url.ToString()))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        try
                        {
                            //Allow updating of some sharepoint lists, (here spUsers, spGroups etc...)
                            spWeb.AllowUnsafeUpdates = true;
                            SPUser spUser = spWeb.EnsureUser(userLoginName);
                            if (spUser != null)
                            {
                                SPGroup spGroup = spWeb.Groups[userGroupName];
                                if (spGroup != null)
                                    spGroup.AddUser(spUser);
                            }
                        }
                        catch (Exception ex)
                        {
                            //Error handling logic should go here
                        }
                        finally
                        {
                            spWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }

No comments:

Post a Comment