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