How to add users as site collection administrator group through code
-
16-10-2019 - |
Question
I am having various site collections and I want to add few users into administrator group. So that more people will have access to edit the groups. I can add users to the site collection administrators group through Site Actions -> Site Collection Administrators (and add users)
But I want to add users into admin group through code? I didn't get much idea about it.
Any help is appreciated.
Thanks.
Solution
There is a big difference with being site collection administrator. While the answer by MBsurf makes a user site admin, that will give him probably to much permissions. Using the code below you can retrieve the Owners group of a site and then add a user to that group:
// get the owners group based on permission
var ownerAssignment = (from a in site.RootWeb.RoleAssignments.OfType<SPRoleAssignment>()
where a.RoleDefinitionBindings.OfType<SPRoleDefinition>().
Contains(site.RootWeb.RoleDefinitions.GetByType(SPRoleType.Administrator))
select a).FirstOrDefault();
// get the assignment's SharePoint group
var adminGroup = (SPGroup)ownerAssignment.Member;
// you can now add a user to this group
OTHER TIPS
Check out this post.
Here is the example from the post:
//if the user is not a user on the site already
someSPWeb.AllUsers.Add(“domain\\user”,”user@domain.com”,”The User”,null);
SPUser spUser = someSPWeb.AllUsers["domain\\user"];
spUser.IsSiteAdmin = true;
spUser.Update();
The below property is more effective to retrieve the site (SPWeb) owner group:
SPWeb.AssociatedOwnerGroup
Regards,
Vinicius