Link to home
Start Free TrialLog in
Avatar of mshaji
mshajiFlag for India

asked on

Add a user to Owner Group programmatically

Dears,

I have 60 sub sites under a site collection and each sub site have "Owner Group" permission (SharePoint permission group). Now here I needed to add a user to this group programmatically. Here adding it manually to these sub sites are much time taking. So can anyone give an idea to add a user to these sub sites together  by C# coding.

Regards

Shaji
Avatar of meloy_31
meloy_31

test
Follow the below code.

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;
                        }
                    }
                }

            });
        }
ASKER CERTIFIED SOLUTION
Avatar of mshaji
mshaji
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mshaji

ASKER

solved