The snippet shows, how to remove user from SharePoint group. "RemoveUserFromSPGroup" method accepts 3 parameters as SPSite object, LoginName of the user and Group name.
//Removes user from SPGroup
public static void RemoveUserFromSPGroup(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.RemoveUser(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";
RemoveUserFromSPGroup(currentSite,loginName,"Group Visitors")
Output:
Removes "Domain\LoginName" user from "Group Visitors" group
Explanation:
In the code we are using
- SPSecurity.RunWithElevatedPrivileges - executes code with full control
- AllowUnsafeUpdates to true - Because we are removing user from SPGroup so AllowUnsafeUpdates allow updates to the web.